How to Sort a Dictionary by Value in Python

Introduction

Sorting a dictionary by its values is a common task in Python. The dictionary, which is a key-value data structure, does not have an inherent order. However, there are multiple ways to sort a dictionary by its values. In this article, we will explore different approaches to solve this problem.

Method 1: Using the sorted() function with a lambda function

The sorted() function in Python can be used to sort any iterable object. We can use this function along with a lambda function to sort a dictionary by its values.

Here's an example to demonstrate this approach:


# Define a dictionary
my_dict = {'apple': 10, 'orange': 5, 'banana': 7}

# Sort the dictionary by its values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))

print(sorted_dict)

        

Output:


{'orange': 5, 'banana': 7, 'apple': 10}

        

In this example, we use the sorted() function with the items() method of the dictionary to create a list of key-value pairs. The lambda function lambda x: x[1] is used as the key parameter of the sorted() function to specify that the sorting should be based on the second element of each tuple (i.e., the values).

Finally, we convert the sorted list of tuples back into a dictionary using the dict() function.

Method 2: Using the operator module

The operator module in Python provides a convenient way to sort a dictionary by its values. We can make use of the itemgetter() function from this module to specify the sorting key.

Here's an example to demonstrate this approach:


# Import the operator module
import operator

# Define a dictionary
my_dict = {'apple': 10, 'orange': 5, 'banana': 7}

# Sort the dictionary by its values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=operator.itemgetter(1)))

print(sorted_dict)

        

Output:


{'orange': 5, 'banana': 7, 'apple': 10}

        

In this example, we import the operator module and use the itemgetter() function as the key parameter of the sorted() function to specify that the sorting should be based on the second element of each tuple.

Method 3: Using the collections module

The collections module in Python provides the OrderedDict class, which is a dictionary subclass that remembers the order of its entries. We can make use of the OrderedDict class to sort a dictionary by its values.

Here's an example to demonstrate this approach:


# Import the collections module
from collections import OrderedDict

# Define a dictionary
my_dict = {'apple': 10, 'orange': 5, 'banana': 7}

# Sort the dictionary by its values in ascending order
sorted_dict = OrderedDict(sorted(my_dict.items(), key=lambda x: x[1]))

print(sorted_dict)

        

Output:


OrderedDict([('orange', 5), ('banana', 7), ('apple', 10)])

        

In this example, we import the OrderedDict class from the collections module. We use the sorted() function as before, but now we pass the result to the OrderedDict() function to create a new dictionary that retains the order of the sorted items.

Conclusion

Sorting a dictionary by its values is a common task in Python. In this article, we explored three different approaches to solve this problem: using the sorted() function with a lambda function, using the operator module, and using the collections module.

By applying these methods, you can easily sort a dictionary by its values in ascending order. You can also modify the examples to sort in descending order by using the reverse=True parameter in the sorted() function.

Remember that dictionaries in Python are unordered by nature, so the order of the keys does not necessarily match the order of the values after sorting. If you need to preserve the order, you can use the OrderedDict class from the collections module.