Sorting a dictionary by value in Python
Start your free 7-days trial now!
To sort a dictionary by value in Python use the sorted(~) built-in function.
This only works with Python 3.7+ as before this dictionaries did not preserve insertion order.
Example
Consider the following dictionary:
d1 = {"C": 3, "B": 2, "A": 1}
Ascending order
To sort the dictionary in ascending order of value:
Let us explain the above by breaking it down into a few parts. The iterable we are passing to sorted(~) for sorting is d1.items():
dict_items([('C', 3), ('B', 2), ('A', 1)])
We sort the above iterable according to the lambda function provided as the key. Here the lambda function states that we want to sort on the second item item[1] within each tuple item. This means we sort the tuples according to their second items (3, 2, and 1) in ascending order.
Finally we pass the result to dict() constructor to create the dictionary that we return.
Descending order
To sort the dictionary in descending order of value:
By passing reverse=True we sort in descending order.