Sub topic 5
Tuples as Dictionary Keys and Set Members
This chapter assumes you know basic dictionaries and sets, tuple creation and indexing, and that tuples are immutable. It explains why tuples can be dictionary keys and set members, and when they can't.
Why keys must be hashable
A dictionary finds a key by computing its hash, an integer produced by hash(). A set does the same for its members. Two rules make this work:
- Equal objects must have equal hashes.
- An object's hash must not change while it is stored.
Lists break the second rule, because you can change their contents. Python therefore makes lists unhashable, and they cannot be keys or set members. Tuples can't change their own items, so they can be hashed.
Tuples as keys
A tuple is a natural way to build one key from several values, such as grid coordinates or a (city, year) pair.
grid = {(0, 0): "start", (2, 3): "goal"}
print(grid[(2, 3)])
grid[(1, 1)] = "wall"
print((0, 0) in grid)
print(grid.get((9, 9), "empty"))The lookup uses the whole tuple. (2, 3) is a different key from (3, 2), because tuples compare item by item in order.
Tuples in sets
Sets store each distinct value once. A set of tuples is a common way to track visited positions or remove duplicate records.
visited = set()
for step in [(0, 0), (0, 1), (0, 0), (1, 1)]:
if step in visited:
print("again", step)
visited.add(step)
print(len(visited))This prints again (0, 0) and then 3. The membership test step in visited takes roughly constant time, however large the set grows.
The hashability rule for tuples
A tuple's hash is built from the hashes of its items. The tuple is hashable only if every item is hashable. This check is recursive, so it also applies to tuples nested inside tuples.
good = (1, "a", (2, 3))
bad = ([0, 0], 1)
print(hash(good) == hash((1, "a", (2, 3))))
try:
hash(bad)
except TypeError as e:
print(e)The first line prints True, because equal tuples have equal hashes. The second prints unhashable type: 'list'. Using bad as a key or set member fails with the same TypeError.
Fixing an unhashable tuple
If an item is a list, convert it to a tuple before you use the result as a key.
route = [0, 0]
key = (tuple(route), 1)
lookup = {key: "x"}
print(lookup[((0, 0), 1)])This works because (0, 0) is a tuple of integers. The conversion makes a copy, so later changes to route do not affect the key.
Equality across types
Keys match by equality, not by type. Since 1 == 1.0 is True and their hashes agree, (1, 2) and (1.0, 2) are the same key.
d = {(1, 2): "int"}
d[(1.0, 2)] = "float"
print(d)The dictionary still has one entry. It keeps the original key (1, 2) and replaces its value, so it prints {(1, 2): 'float'}.
Summary
- Tuples hash by their contents, so equal tuples are the same key.
- A tuple works as a key or set member only if all of its items are hashable.
- Convert lists to tuples before using them inside a key.
Exercise
Which of these raises a TypeError when used as a dictionary key, and why? (a) (1, 2) (b) ("a", (1, 2)) (c) (1, [2, 3])
Show answer
Only (c). It contains a list, which is unhashable, so the tuple cannot be hashed. Option (a) holds only integers. Option (b) holds a string and a tuple of integers, and every item is hashable.
Exercise
Write code that takes the list of pairs [[1, 2], [3, 4], [1, 2]] and prints how many distinct pairs it contains.
Show answer
print(len({tuple(p) for p in [[1, 2], [3, 4], [1, 2]]})) prints 2. Each inner list is converted to a tuple so it can go into the set, and the duplicate [1, 2] collapses into one member.