4

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)])
falsetru
  • 357,413
  • 63
  • 732
  • 636
wasp256
  • 5,943
  • 12
  • 72
  • 119
  • Like falsetru mentioned ordered dict orders them in the order that they are entered. You could also convert the keys to datetime objects then put them into the ordered dict. Here is the original post. https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value – Joe Jul 01 '17 at 13:06
  • See [sortedcontainers](https://pypi.python.org/pypi/sortedcontainers). – phd Jul 01 '17 at 13:26

1 Answers1

7

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)])
falsetru
  • 357,413
  • 63
  • 732
  • 636