How do I sort a dictionary by value?
Ever wondered how to reorder a dictionary based on its values instead of keys? Let's explore a simple and effective way to sort a dictionary by value using Python’s built-in functions.
Absolutely! Sorting a dictionary by its values in Python is a common task, especially when you need to organize data based on importance, frequency, or size. But since dictionaries themselves are unordered collections (prior to Python 3.7), you’ll need to use a little trick with sorted().
Here's a quick and human-friendly way to do it:
Let’s say you have this dictionary:
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8}
If you want to sort it by values (low to high):
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)
To sort in reverse (high to low):
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
Key Points to Remember:
- .items() returns key-value pairs.
- key=lambda item: item[1] tells sorted() to sort by the value.
- Wrapping with dict() converts the result back into a dictionary.
Why this matters:
- Perfect for leaderboard rankings, frequency counts, or organizing config settings.
- Cleaner and more Pythonic than writing a loop manually.
This little trick is one of those Python gems that makes your code both efficient and elegant.