2017-08-09 424 views
0

的理解行爲我有星期幾的有序詞典:需要幫助Ordereddict

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

我想第n個鍵的值更改爲1,所以如果我n設置爲4,第4個鍵是'星期四',所以平日裏就變成了:

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 

,似乎工作,但如果I W螞蟻在第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

因爲你正在做的詞彙比較沒有的數字順序,'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)])