How to Sort a Dictionary by Value in Python
Suppose we have a dictionary that contains unsorted values.
unsorted_dict = {
"one": 1,
"zero": 0,
"three": 3,
"two": 2
}
We want to sort this dictionary based on these values to get this resulting sorted dictionary.
sorted_dict = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3
}
We can use the sorted()
function to achieve this.
sorted_dict = dict(sorted(unsorted_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # {'zero': 0, 'one': 1, 'two': 2, 'three': 3}
We can sort descending just by adding reverse=True
.
sorted_dict = dict(sorted(unsorted_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict) # {'three': 3, 'two': 2, 'one': 1, 'zero': 0}
Finally, we can get the same ascending, sorted result using dictionary comprehension.
sorted_dict = {k: v for k, v in sorted(unsorted_dict.items(), key=lambda item: item[1])}
print(sorted_dict) # {'zero': 0, 'one': 1, 'two': 2, 'three': 3}