Sub topic 10
Sorting a dictionary by key or value
This chapter assumes you can loop over items(), write a lambda, and know that a dictionary keeps insertion order. Here you will use those pieces to produce sorted views of a dictionary.
Dictionaries have no sort method
A dictionary has no sort() method, because its order is the order you inserted entries. To get a different order, you call sorted(), which accepts any iterable and returns a new list. Then you either use the list directly or rebuild a dictionary from it.
Sorting by key
Calling sorted() on the dictionary itself gives a list of its keys in order. Sorting items() keeps the values attached to their keys.
scores = {"cy": 85, "ana": 90, "ben": 72}
print(sorted(scores)) # ['ana', 'ben', 'cy']
print(sorted(scores.items())) # [('ana', 90), ('ben', 72), ('cy', 85)]
print(dict(sorted(scores.items()))) # {'ana': 90, 'ben': 72, 'cy': 85}Pairs are tuples, and Python compares tuples element by element. Sorting the pairs therefore sorts by key first. Keys are unique, so the values are never compared.
Sorting by value
To order by value, pass a key function. It receives each pair and returns the value to compare.
scores = {"ana": 90, "ben": 72, "cy": 85}
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(ranked) # [('ana', 90), ('cy', 85), ('ben', 72)]
print(dict(ranked)) # {'ana': 90, 'cy': 85, 'ben': 72}reverse=True gives the highest value first. The standard library offers operator.itemgetter as a faster, more readable replacement for the lambda:
from operator import itemgetter
scores = {"ana": 90, "ben": 72, "cy": 85}
print(sorted(scores.items(), key=itemgetter(1)))
# [('ben', 72), ('cy', 85), ('ana', 90)]If you only need the keys in value order, sort the dictionary directly and use scores.get as the key function:
print(sorted(scores, key=scores.get)) # ['ben', 'cy', 'ana']Breaking ties
Python's sort is stable. Items that compare equal keep their original relative order. When you want a defined tie-breaker, return a tuple from the key function. Negating a number reverses that part of the order.
grades = {"ben": 80, "ana": 80, "cy": 95}
result = sorted(grades.items(), key=lambda kv: (-kv[1], kv[0]))
print(result) # [('cy', 95), ('ana', 80), ('ben', 80)]This sorts by value descending, then by key ascending. Negation only works for numbers. For strings, sort in two passes, relying on stability: sort by the secondary key first, then by the primary key.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `sorted(d)` when you wanted pairs | You get only the keys | Use `sorted(d.items())` |
| `sorted(d.values())` when you wanted pairs | The values are sorted and the keys are lost | Sort `d.items()` with a key function |
| Expecting `d` to change | `sorted()` returns a new object and leaves `d` alone | Assign the result to a name |
| Keys of mixed types, such as `1` and `"a"` | `TypeError`, because `int` and `str` cannot be ordered | Convert keys, or pass `key=str` |
| Adding entries after sorting | New entries go at the end | Sort again when you need the order |
The last row matters in practice. A "sorted dictionary" is an ordinary dictionary whose insertion order happened to be sorted. It does not stay sorted. If you need sorted output only for display, keep the list of pairs and skip the dict() call.
Top results
To get only the best few entries, slice the sorted list. For large dictionaries, heapq.nlargest avoids sorting everything.
import heapq
scores = {"ana": 90, "ben": 72, "cy": 85, "dee": 60}
print(sorted(scores.items(), key=itemgetter(1), reverse=True)[:2])
# [('ana', 90), ('cy', 85)]
print(heapq.nlargest(2, scores.items(), key=itemgetter(1)))
# [('ana', 90), ('cy', 85)]Counter.most_common(n) from the counting chapter does the same job for tallies.
Exercise
Given stock = {"pear": 5, "apple": 5, "kiwi": 9}, write one expression that returns a dictionary ordered by quantity descending, with ties broken by name ascending. What does it print?
Show answer
dict(sorted(stock.items(), key=lambda kv: (-kv[1], kv[0]))) gives {'kiwi': 9, 'apple': 5, 'pear': 5}. The key function returns (-quantity, name). Kiwi has the largest quantity, so it comes first. Apple and pear tie at 5, so the name decides, and apple sorts before pear.