Sometimes, we want to sort a Python dictionary by value.
In this article, we’ll look at how to sort a Python dictionary by value.
How to sort a Python dictionary by value?
To sort a Python dictionary by value, we can use the call sorted
on the dictionary items.
For instance, we write:
x = {'a': 2, 'b': 4, 'c': 3, 'd': 1, 'e': 0}
sorted_dict = { k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(sorted_dict)
to get the items from x
with x.items
.
Then we call sorted
on it with a function that gets the value with item[1]
to sort the entries by the value of each entry.
Finally, we use the comprehension syntax to put the items into a new dictionary.
Therefore, sorted_dict
is {'e': 0, 'd': 1, 'a': 2, 'c': 3, 'b': 4}
.
Conclusion
To sort a Python dictionary by value, we can use the call sorted
on the dictionary items.