How to Sort a Python Dictionary by Value Descending
Sort dictionary items by their values in descending order and return a new dictionary.
Python code
8 linesdef sort_dict_by_value_desc(d):
return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
if __name__ == "__main__":
sample = {"apple": 5, "banana": 2, "cherry": 8, "date": 8}
result = sort_dict_by_value_desc(sample)
print(result)
Output
{'cherry': 8, 'date': 8, 'apple': 5, 'banana': 2}
How it works
d.items() returns a view of (key, value) pairs. sorted() takes an iterable and an optional key function to extract the sort key; here we use item[1] to grab the value. Setting reverse=True sorts in descending order. Finally, dict() converts the sorted list of tuples back into a dictionary. Since Python 3.7 dictionaries preserve insertion order, the sorted order is retained.
Common mistakes
- Forgetting `reverse=True` — this sorts ascending by default.
- Modifying the original dictionary in place when you only need a sorted copy.
- Using `dict(sorted(d))` without a key, which sorts by keys instead of values.
Variations
- Use `operator.itemgetter(1)` instead of a lambda for slightly better performance: `sorted(d.items(), key=itemgetter(1), reverse=True)`.
- For just the sorted keys or values, use `sorted(d, key=d.get, reverse=True)` or `sorted(d.values(), reverse=True)`.
Real-world use cases
- Displaying top products by sales in an e-commerce dashboard.
- Ranking user scores in a leaderboard retrieved from a database.
- Sorting configuration thresholds by their alert severity levels before processing.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.