How to Sort a Python Dictionary by Value Descending

Sort dictionary items by their values in descending order and return a new dictionary.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
{'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

  1. Use `operator.itemgetter(1)` instead of a lambda for slightly better performance: `sorted(d.items(), key=itemgetter(1), reverse=True)`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.