python按时间顺序排序OrderedDict键

时间:2017-07-01 12:55:51

标签: python sorting dictionary ordereddictionary

我有以下OrderedDict

 from collections import OrderedDict
 a = OrderedDict()
 a['2016:April'] = 1
 a['2016:January'] = 2
 a['2017:February'] = 3
 a['2015:November'] = 4

我想按时间顺序按键排序字典,结果是:

 OrderedDict([('2015:November', 4), ('2016:January', 2), ('2016:April', 1), ('2017:February', 3)])

1 个答案:

答案 0 :(得分:7)

您需要通过传递已排序的项目来重新创建OrderedDict; (OrderedDict记住密钥插入顺序)

import calendar
from collections import OrderedDict

months = {calendar.month_name[i]: i for i in range(1, 13)}
# => {'January': 1, 'February': 2,  .... 'December': 12}
def get_month_from_key(item):
    # Convert '2015:November' to (2015, 11)
    # Return value of this function is used to compare dictionary keys.
    year, month = item[0].split(':')  # item[0] is key
    return int(year), months.get(month, -1)

a = OrderedDict()
a['2016:April'] = 1
a['2016:January'] = 2
a['2017:February'] = 3
a['2015:November'] = 4

a = OrderedDict(sorted(a.items(), key=get_month_from_key))
# => OrderedDict([('2015:November', 4), ('2016:January', 2),
#                 ('2016:April', 1), ('2017:February', 3)])