python sort OrderedDict keys chronologically

2019-06-24 05:41发布

I have the following OrderedDict:

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

I would like to sort the dictionary by the keys in chronological order so that the result is:

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

1条回答
闹够了就滚
2楼-- · 2019-06-24 05:57

You need to recreate the OrderedDict by passing sorted items; (OrderedDict remembers key insertion order)

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)])
查看更多
登录 后发表回答