In Python, dictionaries are unordered collections of key-value pairs. Although dictionaries themselves cannot be sorted, we can extract their keys and values, sort them according to their values, and display the sorted key-value pairs in various ways. In this blog post, we will explore how to sort a dictionary by value in Python using different techniques and examples.
Using the sorted() Function and Lambda
One common approach to sort a dictionary by value is to use the built-in sorted() function along with a lambda function as the key. The sorted() function takes an iterable (e.g., a list, tuple, or dictionary) as input and returns a sorted list.
The lambda function helps to specify the sorting criteria. In our case, we want to sort the dictionary according to its values. Here’s an example:
sample_dict = {‘apple’: 5, ‘orange’: 3, ‘banana’: 8, ‘grape’: 1}
# Sort dictionary by value
sorted_dict = sorted(sample_dict.items(), key=lambda x: x[1])
print(sorted_dict)
In this example, sample_dict.items() returns a view object displaying a list of the dictionary’s key-value tuple pairs. The key=lambda x: x[1] parameter in the sorted() function sorts these items based on their values (i.e., x[1] in the lambda function).
The output of the sorted dictionary will be:
[('grape', 1), ('orange', 3), ('apple', 5), ('banana', 8)]
Sorting in Descending Order
If you want to sort the dictionary by value in descending order, you can add reverse=True as an argument in the sorted() function. Here’s an example:
sorted_dict_desc = sorted(sample_dict.items(), key=lambda x: x[1], reverse=True)
print(sorted_dict_desc)
The output will be:
[('banana', 8), ('apple', 5), ('orange', 3), ('grape', 1)]
Using the operator Module
Another way to sort a dictionary by value is to use the operator module. The module has a function called itemgetter() that can replace the lambda function as the key in the sorted() function. Here’s an example:
# Sort dictionary by value
sorted_dict_operator = sorted(sample_dict.items(), key=operator.itemgetter(1))
print(sorted_dict_operator)
The output will be the same as in the first example:
[('grape', 1), ('orange', 3), ('apple', 5), ('banana', 8)]
Conclusion
In this post, we have explored different techniques to sort a dictionary by value in Python. While using the sorted() function with a lambda function or the operator.itemgetter() function are the most common methods, it’s essential to choose the approach that best suits your needs and coding preferences.