How to Sort a Dictionary by Value

Python dictionary is an order-less data type, therefore, you could not sort the dictionary by its keys or values. But you could get the representation of sorted Python dictionary in other data type like list.

Assume we have a dictionary like below,

exampleDict = {'first': 3, 'second': 4, 'third': 2, 'fourth': 1}

Only get the sorted values

sortedDict = sorted(exampleDict.values())
#Out: [1, 2, 3, 4]

Using operator.itemgetter to sort the dictionary

import operator
sortedDict = sorted(exampleDict.items(), key=operator.itemgetter(1))
#Out: [('fourth', 1), ('third', 2), ('first', 3), ('second', 4)]

exampleDict.items returns the key-value pair of dictionary elements. key=operator.itemgetter(1) specifies the comparison key is the value of the dictionary, meanwhile operator.itemgetter(0) has the comparison key of the dictionary key.

Using lambda function in the key of sorted to sort the dictionary

You could also lambda function to get the comparison key instead of operator.itemgetter

sortedDict = sorted(exampleDict.items(), key=lambda x: x[1])
#Out: [('fourth', 1), ('third', 2), ('first', 3), ('second', 4)]

exampleDict.items() returns a list of key-value pairs of the dictionary and its element’s data type is tuple. x is the element of this tuple, where x[0] is the key and x[1] is the value. key=lambda x:x[1] indicates the comparison key is the value of the dictionary elements.

OrderedDict to get the dictionary-compatible result

The example code shown above returns the result as a list, but not a dictionary type. If you want to keep the result as dictionary-compatible type, OrderedDict introduced from Python 2.7 is the right choice.

from collections import OrderedDict
sortedDict = OrderedDict(sorted(exampleDict.items(), key=lambda x: x[1]))
#Out: OrderedDict([('fourth', 1), ('third', 2), ('first', 3), ('second', 4)])

The OrderedDict is a Python dict subclass that supports the usual methods and also remembers the order that keys are first inserted.