Thursday, December 10, 2015

Sort Python dictionaries by key

Even though dictionaries in Python are unordered, we can use this following technique to sort the dictionaries:


>>> import collections

>>> d = {2:3, 1:89, 4:5, 3:0}

>>> od = collections.OrderedDict(sorted(d.items()))

>>> od
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

And the best thing is we can still using that collection just like our old dictionary:

>> od[1]
89

>>> for k, v in od.iteritems(): print k, v
1  89
2  3
3  0
4  5

Note: the only difference is that we use iteritems() instead of items(). But it will be the same in python 3 (items())

References: http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key