How to Sort a Python Dictionary by Value?
There are multiple ways to sort a Python dictionary by value. Here are a few examples:
Method 1: Using the sorted() function and itemgetter()
from operator import itemgetter
my_dict = {'a': 5, 'b': 2, 'c': 10, 'd': 1}
sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(1)))
print(sorted_dict)
Output:
{'d': 1, 'b': 2, 'a': 5, 'c': 10}
Here, we first use the items() method to get a list of key-value pairs in the dictionary, and then we use the sorted() function to sort this list by the second element (the value) of each tuple. The key=itemgetter(1) argument tells the sorted() function to use the second element of each tuple as the sorting key. Finally, we use the dict() constructor to convert the sorted list back into a dictionary.
Method 2: Using a lambda function and the sorted() function
my_dict = {'a': 5, 'b': 2, 'c': 10, 'd': 1}
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print(sorted_dict)
Output:
{'d': 1, 'b': 2, 'a': 5, 'c': 10}
This method is similar to Method 1, but we use a lambda function instead of itemgetter() to extract the second element of each tuple.
Method 3: Using a list comprehension and the sorted() function
my_dict = {'a': 5, 'b': 2, 'c': 10, 'd': 1}
sorted_items = sorted(my_dict.items(), key=lambda x: x[1])
sorted_dict = {k: v for k, v in sorted_items}
print(sorted_dict)
Output:
{'d': 1, 'b': 2, 'a': 5, 'c': 10}
In this method, we first use the sorted() function to sort the items in the dictionary by value, and we store the result in a list of tuples called sorted_items. We then use a dictionary comprehension to convert this list of tuples back into a dictionary.