Reputation: 45
I have a python dictionary like
{'JUL':15,'MAR': 54,'DEC':65,'OCT':90}
I want it to be sorted according to months say, MAR, JUL, OCT and DEC in python.
How can I do it?
Upvotes: 3
Views: 4812
Reputation: 152587
You want to sort them by the number of the month so you need to create a Mapping from your month abbreviations to the number of that month:
dic = {'JUL':15, 'MAR': 54,'DEC':65,'OCT':90}
import calendar
month_numeric_mapping = {abb: index for abb in dic
for index, long in enumerate(calendar.month_name[1:])
if str.lower(abb) in str.lower(long)}
>>> month_numeric_mapping
{'DEC': 11, 'JUL': 6, 'MAR': 2, 'OCT': 9}
Then you define a function that can be used with sorted
to get that number:
def getMonthNumber(item):
return month_numeric_mapping[item[0]]
and finally you need to have a order-aware dictionary OrderedDict
to store the sorted output:
>>> from collections import OrderedDict
>>> a = OrderedDict(sorted(dic.items(), key=getMonthNumber))
>>> a
OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)])
calendar.month_abbr
:
month_numeric_mapping = {abbr.upper(): i for i, abbr in enumerate(calendar.month_abbr[1:])}
def getMonthNumber(item):
return month_numeric_mapping[item[0]]
a = OrderedDict(sorted(dic.items(), key=getMonthNumber))
>>> a
OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)])
Upvotes: 4
Reputation: 43235
Dictionaries are orderless, you cannot sort a dictionary. You would need an ordereddict, which you can create from a list of sorted tuples of key,value pairs of your current dict.
>>> months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
>>> input = {'JUL':15,'MAR': 54,'DEC':65,'OCT':90}
>>> from collections import OrderedDict
>>> OrderedDict(sorted(input.items(),key =lambda x:months.index(x[0])))
OrderedDict([('MAR', 54), ('JUL', 15), ('OCT', 90), ('DEC', 65)])
Upvotes: 7
Reputation: 546
A key sort function like the PHP ksort()
:
def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys
for k in ksort(dic):
print k, d[k]
Upvotes: -1
Reputation: 1402
You can use Ordered Dictionaries in Python using collections module. See the below example.
import collections
print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
for k, v in d.items():
print k, v
print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
for k, v in d.items():
print k, v
Output
Regular dictionary:
a A
c C
b B
e E
d D
OrderedDict:
a A
b B
c C
d D
e E
Upvotes: 0