python 按时间顺序对 OrderedDict 键进行排序

python sort OrderedDict keys chronologically

我有以下 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)])

您需要通过传递已排序的项目来重新创建 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)])