Sub topic 8
Frozensets and tuples as composite keys
This chapter assumes you know how dicts and sets work and that you have met hashability (an object can be a dict key only if it has a stable hash). It builds on that to show how to use several values together as one key.
The problem: one key made of several values
Sometimes a single value does not identify a record. A grid cell needs a row and a column. A road between two cities needs both city names. A dict key must be hashable, so a list such as [2, 3] cannot serve as a key. Python gives you two immutable containers that can: the tuple and the frozenset.
Tuples as ordered keys
A tuple is hashable when every element inside it is hashable. Use a tuple when the position of each part has meaning.
grid = {(0, 0): "start", (2, 3): "goal"}
x, y = 2, 3
print(grid[(x, y)]) # goal
print(grid.get((3, 2))) # None, because (3, 2) is a different key than (2, 3)Order is part of a tuple's identity, so (2, 3) and (3, 2) are different keys. That is correct for coordinates. It is a bug if you meant "the pair of cities, in either direction".
Parentheses are optional in a subscript, so grid[2, 3] is the same as grid[(2, 3)].
Frozensets as unordered keys
A frozenset is an immutable set. It has no add or remove, and it is hashable if its elements are hashable. Two frozensets are equal when they contain the same elements, regardless of the order you wrote them in.
distances = {}
distances[frozenset({"Oslo", "Rome"})] = 2000
print(distances[frozenset({"Rome", "Oslo"})]) # 2000
print(frozenset({"a", "b"}) == frozenset({"b", "a"})) # True
same_city = frozenset({"Oslo", "Oslo"})
print(len(same_city)) # 1, because duplicates collapseThe last two lines show a trade-off. A frozenset ignores order, but it also ignores repeats. A route from a city to itself becomes a one-element key. If that case matters, handle it explicitly or use a tuple.
Sets of sets need frozensets
An ordinary set is mutable, so it cannot be an element of another set. A frozenset can.
groups = {frozenset({1, 2}), frozenset({2, 1}), frozenset({3})}
print(len(groups)) # 2, because the first two are equal
try:
nested = {{1, 2}, {3}}
except TypeError as e:
print(e) # unhashable type: 'set'This is the usual way to deduplicate groups, such as a collection of friend pairs, when the order inside each group does not matter.
Set operators on a frozenset return a frozenset. The result takes the type of the left operand.
fs = frozenset({1, 2})
combined = fs | {3}
print(type(combined).__name__) # frozenset
print(sorted(combined)) # [1, 2, 3]Hashable only if everything inside is hashable
Putting a tuple in a key position does not guarantee it works. Python computes the hash from the contents. If any element is unhashable, the whole tuple is unhashable.
try:
bad = {(1, [2, 3]): "x"}
except TypeError as e:
print(e) # unhashable type: 'list'
ok = {(frozenset({"a", "b"}), 3): "mixed key"}
print(ok[(frozenset({"b", "a"}), 3)]) # mixed keyThe error appears when you use the tuple as a key, not when you build the tuple. Building (1, [2, 3]) is fine. This is why a tuple holding a list can sit in a variable without trouble and then fail the first time you use it as a key.
You can mix the two types. A tuple can hold a frozenset, and a frozenset can hold tuples, as long as the innermost values are hashable.
Quick comparison
| Need | Use | Order matters | Repeats kept |
|---|---|---|---|
| Coordinates, (row, column) | `tuple` | Yes | Yes |
| Unordered pair or group | `frozenset` | No | No |
| Unordered but repeats matter | `tuple(sorted(...))` | Normalized by sorting | Yes |
Exercise
You store the travel time between two cities in a dict. A lookup for ("Rome", "Oslo") fails even though you stored ("Oslo", "Rome"). Name two ways to fix the key so both directions find the same entry, and say when each one is the wrong choice.
Show answer
Use frozenset({a, b}) as the key, or use tuple(sorted((a, b))). The frozenset is the wrong choice if a and a can be the same value and you need to tell that apart from a single-city entry, because duplicates collapse to one element. The sorted tuple is the wrong choice if the values cannot be compared with each other, since sorted would raise a TypeError.