How to Sort a Dictionary by Value in Python
dict(sorted(d.items(), key=lambda item: item[1])) to sort a dictionary by value, and add reverse=True for descending order. A dictionary has no sort method, so you sort its items and build a new dictionary.Leaderboards, price lists and word counts all need the same operation: show the entries ordered by their values instead of their keys. Python dictionaries remember insertion order, so to sort one you create a new dictionary whose items are inserted in the order you want.
The recipe relies on dict.items() to get (key, value) pairs and on sorted() with a key function that tells Python to compare the second element of each pair.
| Ascending | dict(sorted(d.items(), key=lambda kv: kv[1])) |
|---|---|
| Descending | add reverse=True |
| Returns | A new dictionary; the original is unchanged |
| Needs | Python 3.7+ so the new dictionary keeps the sorted order |
| Time complexity | O(n log n) |
Sort a dictionary by value in ascending order
d.items() yields pairs like ("Asha", 82). The key function receives one pair and returns the part to sort by, here index 1, the value. sorted() returns a list of pairs in the new order and dict() turns that list back into a dictionary.
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
by_score = dict(sorted(scores.items(), key=lambda kv: kv[1]))
print(by_score)If lambda functions are new to you, kv[1] simply means "the second item of the pair".
Sort by value in descending order and get the top N
Pass reverse=True to put the largest values first. To keep only the best few entries, slice the sorted list before converting it. Equal values keep their original relative order because sorted() is stable.
scores = {"Asha": 82, "Ben": 91, "Chen": 75, "Dara": 88}
best = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
print(best)Use operator.itemgetter instead of a lambda
operator.itemgetter(1) does the same job as lambda kv: kv[1] and is a little faster and easier to read once you know it.
from operator import itemgetter
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
by_score = dict(sorted(scores.items(), key=itemgetter(1)))
Other things you can sort by
| Goal | Code | Result type |
|---|---|---|
| Keys ordered by value | sorted(d, key=d.get) | list of keys |
| Values only, sorted | sorted(d.values()) | list of values |
| Pairs by value | sorted(d.items(), key=lambda kv: kv[1]) | list of tuples |
| Dictionary by value | dict(sorted(d.items(), key=lambda kv: kv[1])) | dict |
| Dictionary by key | dict(sorted(d.items())) | dict |
Examples you can run
Press Run, then edit the code and run it again.
Ascending order by value
The lowest score comes first.
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
print(dict(sorted(scores.items(), key=lambda kv: kv[1])))Expected output{'Chen': 75, 'Asha': 82, 'Ben': 91}
Descending order by value
Add reverse=True for a leaderboard.
scores = {"Asha": 82, "Ben": 91, "Chen": 75}
ranking = dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
print(ranking)
print(next(iter(ranking)))Expected output{'Ben': 91, 'Asha': 82, 'Chen': 75}
Ben
Only the keys, ordered by value
sorted(d, key=d.get) loops over keys and uses d.get to look up each value.
stock = {"pen": 40, "ink": 5, "book": 12}
print(sorted(stock, key=stock.get))Expected output['ink', 'book', 'pen']
Ties keep their original order
sorted() is stable, so equal values stay in the order they had in the dictionary.
votes = {"red": 3, "blue": 3, "green": 1}
print(dict(sorted(votes.items(), key=lambda kv: kv[1], reverse=True)))Expected output{'red': 3, 'blue': 3, 'green': 1}
Common mistakes
Sorting the dictionary directly
✗ Wrong
scores = {"Asha": 82, "Ben": 91}
print(sorted(scores))✓ Right
scores = {"Asha": 82, "Ben": 91}
print(dict(sorted(scores.items(), key=lambda kv: kv[1])))sorted(d) iterates over keys. Sort d.items() with a key to order by value.
Calling a sort method on a dictionary
✗ Wrong
scores = {"Asha": 82}
scores.sort()✓ Right
scores = {"Asha": 82}
scores = dict(sorted(scores.items(), key=lambda kv: kv[1]))Dictionaries have no sort(). Use sorted() and build a new dictionary.
Mixing value types
✗ Wrong
data = {"a": 1, "b": "two"}
sorted(data.items(), key=lambda kv: kv[1])✓ Right
data = {"a": 1, "b": "2"}
print(sorted(data.items(), key=lambda kv: int(kv[1])))All values you compare must be comparable. Convert them first, for example key=lambda kv: int(kv[1]).
How to Sort a Dictionary by Value in Python: questions people ask
How do I sort a dictionary by value in descending order in Python?
Call dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True)). The reverse=True argument puts the largest values first.
Can a Python dictionary actually be sorted?
Not in place, but since Python 3.7 dictionaries keep insertion order, so a new dictionary built from sorted items stays sorted. Dictionaries have no sort() method.
How do I sort a dictionary by key instead of value?
Use dict(sorted(d.items())). Pairs compare by their first element, the key, by default.
Keep learning
Step-by-step lessons:
Python DictionariesPython SortingPython Lambda Functions
Related:
Python sorted() FunctionPython Dictionary items() MethodHow to Loop Through a Dictionary in PythonPython sort() vs sorted(): What Is the Difference?
More in lists, dicts and sets:
How to Remove Duplicates from a List in PythonHow to Merge Two Dictionaries in PythonHow to Reverse a List in PythonHow to Flatten a List of Lists in PythonHow to Check if a List Is Empty in PythonHow to Get the Last Element of a List in PythonHow to Loop Through a Dictionary in PythonHow to Count Occurrences in a List in Python See all →