Search code examples
python-3.xordereddictionary

Need help understanding behaviour of Ordereddict


I have an ordered dictionary of days of the week:

weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])

I want to change the nth key's value to 1, so if I set n to 4, the 4th key is 'Thu' so weekdays becomes:

OrderedDict([('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 1), ('Fri', 0), ('Sat', 0), ('Sun', 0)])

I can do that with the following code:

startday_2017 = 4
weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])
date = list(weekdays.keys())[(startday_2017-1)]
for key in weekdays.keys():
        if key == date:
            weekdays[key] = 1

That seems to work, but if I want to change the values corresponding to keys before or after the nth key, the ordereddict starts acting funny. With this code:

startday_2017 = 4
weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])
date = list(weekdays.keys())[(startday_2017-1)]
for key in weekdays.keys():
        if key < date:
            weekdays[key] = "applesauce"
        elif key == date:
            weekdays[key] = 1
        else:
            weekdays[key] = 2

print(weekdays)

I get this output:

OrderedDict([('Mon', 'applesauce'), ('Tue', 2), ('Wed', 2), ('Thu', 1), ('Fri', 'applesauce'), ('Sat', 'applesauce'), ('Sun', 'applesauce')])

How do I achieve the result I'm after?


Solution

  • Because you are doing lexical comparison not numerical ordering, 'Tue' > 'Thurs':

    What you might want to try is just to enumerate() the keys and use the numerical value, e.g.:

    In []:
    for i, key in enumerate(weekdays, 1):
        if i < startday_2017:
            weekdays[key] = "applesauce"
        elif i == startday_2017:
            weekdays[key] = 1
        else:
            weekdays[key] = 2
    weekdays
    
    Out[]:
    OrderedDict([('Mon', 'applesauce'),
                 ('Tue', 'applesauce'),
                 ('Wed', 'applesauce'),
                 ('Thu', 1),
                 ('Fri', 2),
                 ('Sat', 2),
                 ('Sun', 2)])