Using two functions together: items() and sorted() can Sort dictionary by value in Python. The items() function allows you to retrieve the elements in a dictionary. And the combination with the sorted() function and a custom key parameter to sort a dictionary by value.
x = {"A": 2, "B": 4, "C": 3, "D": 1, "E": 0}
res = dict(sorted(x.items(), key=lambda item: item[1]))
print(res)
Example sort dictionary by value Python
Simple example code with List Comprehension.
In Python, the dictionary class doesn’t have any provision to sort items in its object, such as the list has able to perform sorting.
Sort in Ascending Order
x = {"A": 2, "B": 4, "C": 3, "D": 1, "E": 0}
res = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(res)
Output:
Sort in Descending Order
Use reverse=True
x = {"A": 2, "B": 4, "C": 3, "D": 1, "E": 0}
res = {k: v for k, v in sorted(x.items(), key=lambda item: item[1], reverse=True)}
print(res)
Output: {‘B’: 4, ‘C’: 3, ‘A’: 2, ‘D’: 1, ‘E’: 0}
Do comment if you have any doubts and suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.