PythonMastery

How do I sort a dictionary by value in Python?

sorted(d.items(), key=lambda kv: kv[1], reverse=True) gives (key, value) pairs, highest first. Wrap it in dict() to get a dictionary back, still in order.

Sort the dictionary's items(), and tell sorted to look at the second half of each pair.

python
scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 95}

ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(ranked)
output
[('Linus', 95), ('Hedy', 95), ('Ada', 82), ('Grace', 77)]

scores.items() gives (name, score) pairs. key=lambda kv: kv[1] says "sort by the score", and reverse=True puts the highest first. Linus and Hedy tie on 95 and keep their original order: Python's sort is stable.

Getting a dictionary back

Since Python 3.7, a dictionary remembers the order keys went in. Rebuild it from the sorted pairs and it stays sorted:

python
scores = {"Ada": 82, "Linus": 95, "Grace": 77}

by_score = dict(sorted(scores.items(), key=lambda kv: kv[1]))
print(by_score)
print(list(by_score)[0], "is lowest")
output
{'Grace': 77, 'Ada': 82, 'Linus': 95}
Grace is lowest

Ties: sort by score, then by name

Return a tuple from the key and Python sorts by the first item, then the second. Negate the number to get "highest score first, then A to Z":

python
scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 95}

for name, score in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0])):
    print(f"{score}  {name}")
output
95  Hedy
95  Linus
82  Ada
77  Grace

Only want the top few?

For the top 3 of a large dictionary, heapq.nlargest skips sorting everything:

python
import heapq

scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 91, "Alan": 60}
print(heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]))
output
[('Linus', 95), ('Hedy', 91), ('Ada', 82)]

If the dictionary holds counts, you probably want a Counter instead, which has most_common(n) built in. And sorted with key= works the same way on any list, not just dictionaries.

Go deeper: Dictionaries, Lambda & Functional Programming, Python Dictionary Cheat Sheet

More short answers

all questions