Sorting a dictionary by value in Python is a common task that can be achieved using the sorted()
function along with a lambda function. Here's a step-by-step guide to do it:
Method 1: Using sorted()
and lambda
1. Sorting in Ascending Order:
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)
2. Sorting in Descending Order:
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)
Method 2: Using operator.itemgetter
1. Sorting in Ascending Order:
import operator
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_dict = dict(sorted(my_dict.items(), key=operator.itemgetter(1)))
print(sorted_dict)
2. Sorting in Descending Order:
import operator
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_dict = dict(sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True))
print(sorted_dict)
Explanation
my_dict.items()
: Returns a view object that displays a list of a dictionary's key-value tuple pairs.key=lambda item: item[1]
: A lambda function that takes a tuple and returns the value part for sorting.reverse=True
: Optional parameter that sorts the dictionary in descending order if set toTrue
.
These methods will help you sort a dictionary by its values efficiently. Choose the one that best fits your coding style and requirements.
Discussion