How to sort a Python dictionary by value?

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 us 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 values, we take 1st element of tuple as key for sorting.

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

The OrderedDict object can be parsed into a regular dictionary object

>>> D1 = dict(OrderedDict(sorted(D.items(), key = lambda t: t[1])))
>>> D1
{4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}
Published on 29-Dec-2017 10:31:37