How do I sort a dictionary by value in Python?

Short answer

Use sorted(d.items(), key=lambda item: item[1]) and pass the result to dict(). Add reverse=True for descending order.

python
views = {"python": 197, "racket": 696, "php": 259}

by_value = dict(sorted(views.items(), key=lambda item: item[1]))
# {'python': 197, 'php': 259, 'racket': 696}

descending = dict(sorted(views.items(), key=lambda item: item[1], reverse=True))
# {'racket': 696, 'php': 259, 'python': 197}

d.items() gives (key, value) pairs. item[1] picks the value as the thing to sort on. dict() rebuilds a dictionary from the sorted pairs — dictionaries have preserved insertion order since Python 3.7, so the order sticks.

#Cleaner with operator.itemgetter

python
from operator import itemgetter
by_value = dict(sorted(views.items(), key=itemgetter(1)))

Slightly faster and arguably clearer than the lambda.

#Sorting by key instead

python
dict(sorted(views.items()))

No key= needed — tuples sort by their first element by default.

#Just the top N

You rarely need the whole thing sorted:

python
top3 = sorted(views.items(), key=itemgetter(1), reverse=True)[:3]

# Or, for large data, the purpose-built tool:
import heapq
heapq.nlargest(3, views.items(), key=itemgetter(1))

#Sorting a list of dictionaries

Same idea, different key function:

python
catalogue.sort(key=lambda v: v["views"], reverse=True)