This post will discuss how to sort a dictionary by its value in Python.

The Python Dictionaries before version 3.7 are unordered. That means even if you sort the dictionary, you can’t store it in a way that preserves the ordering.

1. Using collections.OrderedDict

The idea is to pass the dictionary’s items to the sorted() function, which returns a sorted list of dictionary entries using the specified key. Then you insert the sorted entries into collections.OrderedDict, which remembers the insertion order.

Download  Run Code

 
In Python 3, you can sort the list of tuples by the second element in each tuple as follows:

Download  Run Code

2. Python 3.7+

Before Python 3.7, it was not possible to sort a dictionary. You can use it only to get a sorted representation of a dictionary. With Python 3.7 or CPython 3.6+, the insertion order is now guaranteed in a dictionary. The following example demonstrates.

Download  Run Code

 
To sort it in reverse order, you can pass the reverse argument as True:

Download  Run Code

3. Using collections.Counter class

If the dictionary’s values are numeric, you can use the collections.Counter class to print a dictionary in decreasing order of their values.

Download  Run Code

That’s all about sorting a dictionary by value in Python.

 
Also See:

Sort a dictionary by key in Python