Sort a Dictionary by Value in Python
To sort a dictionary by its values, you can use the sorted()
function along with the key
parameter.
For example:
my_dict = {'a': 4, 'b':2 , 'c':3 , 'd':1 }
sorted_dict = dict(sorted(my_dict.items(), key=lambda item:item[1]))
print(sorted_dict)
Output:
{'d': 1, 'b': 2, 'c': 3, 'a': 4}
Explanation:
my_dict.items()
returns a view of the dictionary’s key-value pairs as tuples in a list.
sorted()
function sorts the items based on the key
parameter.
key=lambda item:item[1]
lambda function specifies that sorting should be based on the second element of each tuple (i.e. value). The first element is key.
dict()
converts the sorted list of tuples back to a dictionary.
Sorting in descending order
To sort a dictionary by values in descending order, you can set the reverse
parameter of the sorted()
function to True
.
For example:
my_dict = {'a': 4, 'b':2 , 'c':3 , 'd':1 }
sorted_dict = dict(sorted(my_dict.items(), key=lambda item:item[1], reverse=True))
print(sorted_dict)
Output:
{'a': 4, 'c': 3, 'b': 2, 'd': 1}
Sorting using collections.OrderedDict
In earlier versions of Python (before 3.7
), dictionaries didn’t preserve insertion order. To ensure the sorted dictionary maintains its order, you can use collections.OrderedDict
.
For example:
from collections import OrderedDict
my_dict = {'a': 4, 'b':2 , 'c':3 , 'd':1 }
# Sort the dictionary by value and store it in an OrderedDict
sorted_dict = OrderedDict(sorted(my_dict.items(), key=lambda item:item[1]))
print(sorted_dict)
Output:
OrderedDict({'d': 1, 'b': 2, 'c': 3, 'a': 4})
Case-insensitive sorting
If your dictionary contains string values and you want to sort them in a case-insensitive manner, you can modify the key
function to convert the values to lowercase (or uppercase) before sorting.
For example:
my_dict = {'b':'Banana', 'a':'apple','d':'Dog', 'c':'cat'}
# Case-insensitive sorting by value
sorted_dict = dict(sorted(my_dict.items(), key=lambda item:item[1].lower()))
print(sorted_dict)
Output:
{'a': 'apple', 'b': 'Banana', 'c': 'cat', 'd': 'Dog'}