需要帮助了解Ordereddict的行为

时间:2017-08-09 19:40:59

标签: python-3.x ordereddictionary

我有一个星期几的有序词典:

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

我想将第n个键的值更改为1,所以如果我将n设置为4,则第4个键为'Thu',因此工作日变为:

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

我可以使用以下代码执行此操作:

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

这似乎有效,但如果我想在第n个键之前或之后更改与键对应的值,则ordereddict开始表现得很有趣。使用此代码:

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)

我得到了这个输出:

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

我如何实现我追求的结果?

1 个答案:

答案 0 :(得分:1)

因为您正在进行词汇比较而不是数字排序,'Tue' > 'Thurs'

您可能想要尝试的只是enumerate()键并使用数值,例如:

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)])