Sub topic 10
Sorting a dictionary by key or value
This chapter assumes you can read and write dictionaries, know that items() yields key-value pairs, and have used lambda and sorted() on lists. Insertion order, which the earlier chapter covers, matters here because it is the only "order" a dictionary has.
The working model: sort a list, then rebuild
A dictionary has no sort method and cannot be sorted in place. Instead, you take its contents out as a sequence, sort that sequence, and optionally build a new dictionary from the result.
sorted() accepts any iterable and always returns a new list. Three details control the result:
keyis a function that takes one element and returns the value to compare. Elements are never changed, only compared through this value.reverse=Trueproduces descending order.- The sort is stable. Elements whose keys compare equal keep their original relative order.
The original dictionary is never modified. Wrapping the sorted pairs in dict() creates a new dictionary whose insertion order matches the sort. This works because dictionaries preserve insertion order (guaranteed since Python 3.7).
Sorting by key
Calling sorted() on a dictionary iterates over its keys, so you get a sorted list of keys.
scores = {"cy": 85, "ana": 90, "ben": 72}
print(sorted(scores)) # ['ana', 'ben', 'cy']
print(sorted(scores, reverse=True)) # ['cy', 'ben', 'ana']
by_key = dict(sorted(scores.items()))
print(by_key) # {'ana': 90, 'ben': 72, 'cy': 85}When sorted() receives items(), it compares the (key, value) tuples. Tuples compare element by element, so the key decides the order. Keys in a dictionary are unique, so the values are never reached in this comparison.
Custom key order
Strings sort by Unicode code point, so uppercase letters come before lowercase ones. Pass a key function to change that.
words = {"banana": 3, "apple": 5, "Cherry": 1}
print(sorted(words)) # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Cherry']
folded = {k: words[k] for k in sorted(words, key=str.lower)}
print(folded) # {'apple': 5, 'banana': 3, 'Cherry': 1}The last line uses a dictionary comprehension over sorted keys. This is an alternative to dict(sorted(...)) that keeps the original key and reads values with a lookup.
Sorting by value
To sort by value, tell sorted() to compare the second element of each pair. A lambda works, and so does operator.itemgetter(1), which does the same job and is slightly faster.
from operator import itemgetter
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)]
ascending = dict(sorted(scores.items(), key=itemgetter(1)))
print(ascending) # {'ben': 72, 'cy': 85, 'ana': 90}You can also sort only the keys by using a lookup as the key function.
scores = {"ana": 90, "ben": 72, "cy": 85}
print(sorted(scores, key=scores.get)) # ['ben', 'cy', 'ana']
print(sorted(scores, key=scores.get, reverse=True)) # ['ana', 'cy', 'ben']
print(sorted(scores.values())) # [72, 85, 90]Here scores.get is called once per key and returns its value. sorted(scores.values()) gives only the values, with no way back to the keys.
| Goal | Expression | Result type |
|---|---|---|
| Keys in order | `sorted(d)` | list of keys |
| Values in order | `sorted(d.values())` | list of values |
| Pairs by key | `sorted(d.items())` | list of tuples |
| Pairs by value | `sorted(d.items(), key=itemgetter(1))` | list of tuples |
| Keys by value | `sorted(d, key=d.get)` | list of keys |
| Sorted dictionary | `dict(sorted(d.items(), ...))` | new dict |
Ties and stability
Because the sort is stable, entries with equal values keep their insertion order. This holds even with reverse=True, which preserves the original order of equal elements instead of flipping it.
scores = {"cy": 90, "dee": 72, "ana": 90, "ben": 72}
print(sorted(scores.items(), key=itemgetter(1), reverse=True)) if False else NoneThat line would work but hides the point, so here is the complete version.
from operator import itemgetter
scores = {"cy": 90, "dee": 72, "ana": 90, "ben": 72}
by_value = sorted(scores.items(), key=itemgetter(1), reverse=True)
print(by_value)
# [('cy', 90), ('ana', 90), ('dee', 72), ('ben', 72)]cy stays ahead of ana and dee stays ahead of ben, because that is the order they were inserted.
Sorting on several criteria
If ties should be broken by something other than insertion order, return a tuple from the key function. Python compares tuples element by element. To sort one criterion descending and another ascending, negate the numeric one.
scores = {"cy": 90, "dee": 72, "ana": 90, "ben": 72}
ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
print(ranked)
# [('ana', 90), ('cy', 90), ('ben', 72), ('dee', 72)]Negation only works for numbers. For descending strings, rely on stability and sort twice: first by the secondary criterion, then by the primary one.
scores = {"cy": 90, "dee": 72, "ana": 90, "ben": 72}
step1 = sorted(scores.items(), key=lambda kv: kv[0], reverse=True) # name, Z to A
step2 = sorted(step1, key=lambda kv: kv[1], reverse=True) # score, high to low
print(step2)
# [('cy', 90), ('ana', 90), ('dee', 72), ('ben', 72)]The second sort does not disturb the name order inside each score group.
Sorting nested dictionaries
When each value is itself a dictionary, the key function reaches into it.
students = {
"ana": {"age": 21, "gpa": 3.9},
"ben": {"age": 19, "gpa": 3.4},
"cy": {"age": 20, "gpa": 3.7},
}
by_gpa = sorted(students.items(), key=lambda kv: kv[1]["gpa"], reverse=True)
print([name for name, _ in by_gpa]) # ['ana', 'cy', 'ben']
youngest_first = dict(sorted(students.items(), key=lambda kv: kv[1]["age"]))
print(list(youngest_first)) # ['ben', 'cy', 'ana']The nested dictionaries are not copied. The new dictionary refers to the same inner objects as the original, so changing youngest_first["ben"]["age"] also changes students["ben"]["age"].
Getting only the top or bottom entries
A full sort costs O(n log n). If you only need the single largest or smallest entry, or a few of them, other tools do less work.
import heapq
from operator import itemgetter
scores = {"ana": 90, "ben": 72, "cy": 85, "dee": 60}
print(max(scores, key=scores.get)) # ana
print(min(scores, key=scores.get)) # dee
top2 = heapq.nlargest(2, scores.items(), key=itemgetter(1))
print(top2) # [('ana', 90), ('cy', 85)]
bottom2 = heapq.nsmallest(2, scores.items(), key=itemgetter(1))
print(bottom2) # [('dee', 60), ('ben', 72)]max() and min() make one pass and return the first match when values tie. heapq.nlargest() is efficient when the number requested is much smaller than the dictionary. When the count approaches the dictionary's size, plain sorted() is as good or better.
Common errors
Mixed types raise TypeError
Python 3 refuses to order values of unrelated types. Sorting keys or values that mix int and str fails.
mixed = {1: "a", "b": "c"}
try:
sorted(mixed)
except TypeError as exc:
print("TypeError:", exc) # '<' not supported between instances of 'str' and 'int'The same error appears when values include None. Give missing values a place in the order by putting a flag first in a tuple.
data = {"a": 3, "b": None, "c": 1}
ordered = sorted(
data.items(),
key=lambda kv: (kv[1] is None, kv[1] if kv[1] is not None else 0),
)
print(ordered) # [('c', 1), ('a', 3), ('b', None)]The flag is False for real values and True for None, so entries with None go last. The 0 placeholder is never compared against real values, because the flag decides first.
Forgetting that sorted() returns a list
sorted(d.items()) gives a list of tuples. Code that then calls .get() or indexes by key fails with an AttributeError or TypeError. Wrap the result in dict() when you need a dictionary again.
Reverse applies to the whole comparison
sorted(d.items(), reverse=True) without a key sorts by key, descending. If you meant descending by value, you must also pass key=itemgetter(1).
A sorted dictionary does not stay sorted
ranked = dict(sorted({"b": 2, "a": 1}.items()))
ranked["0"] = 0
print(list(ranked)) # ['a', 'b', '0']New keys are appended at the end. Updating an existing key keeps its position. If you need sorted output at several points in a program, sort when you read, not when you store.
Decision guide
- Need to print or loop in order once:
for k, v in sorted(d.items()):and no new dictionary. - Need a dictionary whose iteration order is sorted, for example before serializing to JSON:
dict(sorted(d.items(), key=...)). - Need only the best entry or the best few:
max(),min()orheapq. - Need ties broken in a specific way: return a tuple from the key function, or sort twice.
Exercise
Given inventory = {"nut": 40, "bolt": 15, "screw": 40, "washer": 8}, write one expression that returns a list of (name, count) pairs sorted by count from highest to lowest, with ties sorted by name alphabetically. What does it return?
Show answer
sorted(inventory.items(), key=lambda kv: (-kv[1], kv[0])) returns [('nut', 40), ('screw', 40), ('bolt', 15), ('washer', 8)]. The negated count makes larger counts come first, and the name in the second tuple position breaks the tie between nut and screw.
Exercise
A dictionary d = {"x": 3, "y": None, "z": 1} is sorted with sorted(d.items(), key=lambda kv: kv[1]). What happens, and how can you fix it so that None values come last?
Show answer
It raises a TypeError because Python cannot compare None with an int. Use a key function that returns a tuple with a flag first, such as lambda kv: (kv[1] is None, kv[1] if kv[1] is not None else 0). The result is [('z', 1), ('x', 3), ('y', None)].
Exercise
After ranked = dict(sorted(scores.items(), key=itemgetter(1))), you run ranked["new"] = 5. Is ranked still sorted by value? Why or why not?
Show answer
Not necessarily. A new key is appended at the end of the insertion order regardless of its value, so ranked is sorted only up to the moment you added "new". Sort again when you need ordered output.