How to sort a dictionary in Python by keys?

PythonServer Side ProgrammingProgramming

Standard distribution of Python contains collections module. It has definitions of high performance container data types. OrderedDict is a sub class of dictionary which remembers the order of entries added in dictionary object. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

>>> from collections import OrderedDict
>>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'}
>>> OrderedDict(D.items())
 OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])

We also need to use sorted() function that sorts elements in an iterable in a specified order. The function takes a function as argument which is used as key for sorting. Since we intend to sort dictionary on keys, we take 0th element of tuple as key for sorting

>>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'}
>>> OrderedDict(sorted(D.items(), key = lambda t: t[0]))
   OrderedDict([(1, 'ooo'), (2, 'ddd'), (3, 'ttt'), (4, 'bbb'), (5, 'fff')])

The OrderedDict object can be parsed into a regular dictionary object

>>> D1 = dict(OrderedDict(sorted(D.items(), key = lambda t: t[0])))
>>> D1
   {1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}
raja
Published on 28-Dec-2017 05:45:11
Advertisements