Sub topic 5
Tuples as Dictionary Keys and Set Members
This chapter assumes you can create tuples, index them, and use dictionaries and sets at a basic level. You should also know what immutability means for a tuple, as covered in the previous chapter. Here you will see why a tuple can serve as a dictionary key or a set member and a list cannot. You will also see when a tuple loses that ability and which patterns the feature makes easy.
Why keys must be hashable
A dictionary finds a value by computing a number from the key, called its hash, and using that number to jump to a storage slot. A set works the same way for its members. This is why lookups take roughly constant time, however many items are stored.
Python asks a key to follow two rules:
- Two keys that compare equal must have the same hash.
- The hash of a key must not change while the key is in the container.
An object is hashable if it has a hash value that follows these rules. You can test any object with the built-in hash() function. If the object is not hashable, hash() raises TypeError.
Lists, dictionaries and sets are mutable, and equality depends on their contents. If a list's contents changed after you stored it as a key, its hash would change and Python could no longer find it. Python avoids that problem by refusing to hash these types at all.
Tuples as keys
A tuple cannot change its length or rebind its items, so it can be hashed, provided its contents can be hashed too. This makes a tuple a natural key when a value is identified by several parts, such as a grid position.
grid = {(0, 0): "start", (2, 3): "goal"}
print(grid[(2, 3)])
print(grid[2, 3])
try:
bad = {([0, 0], 1): "x"}
except TypeError as e:
print(e)The output is:
goal
goal
unhashable type: 'list'The second lookup shows that the parentheses are optional inside square brackets. grid[2, 3] builds the tuple (2, 3) for you, because a tuple is defined by its commas. The last case fails because the key tuple contains a list.
A tuple is hashable only if every item is
The hash of a tuple is computed from the hashes of its items. A tuple is therefore hashable only when all of its items are hashable, including items nested inside other tuples. The check below shows the rule in action.
candidates = {
"int pair": (1, 2),
"nested tuples": ((1, 2), (3, 4)),
"str and frozenset": ("a", frozenset({1, 2})),
"list inside": ([1, 2], 3),
"dict inside": ({"a": 1},),
"set inside": ({1}, 2),
}
for label, value in candidates.items():
try:
hash(value)
print(f"{label}: hashable")
except TypeError as e:
print(f"{label}: {e}")The output is:
int pair: hashable
nested tuples: hashable
str and frozenset: hashable
list inside: unhashable type: 'list'
dict inside: unhashable type: 'dict'
set inside: unhashable type: 'set'The error names the offending item, not the tuple. Read the message to find which part of the key is mutable.
This table summarizes common types.
| Type | Hashable? | Reason |
|---|---|---|
| `int`, `float`, `bool`, `None` | Yes | Immutable values |
| `str`, `bytes` | Yes | Immutable values |
| `tuple` | Only if all items are | Hash is built from the items |
| `frozenset` | Yes | Immutable version of a set |
| `list`, `dict`, `set` | No | Contents can change |
Tuples as set members
Sets need hashable members for the same reason dictionaries need hashable keys. A set of tuples is a convenient way to track pairs or coordinates, remove duplicates and test membership quickly.
visited = {(0, 0), (0, 1)}
visited.add((0, 1))
visited.add((1, 1))
print(len(visited))
print((1, 1) in visited)
print(visited & {(0, 0), (5, 5)})
pairs = [[1, 2], [3, 4], [1, 2]]
try:
set(pairs)
except TypeError as e:
print(e)
unique = {tuple(p) for p in pairs}
print(sorted(unique))The output is:
3
True
{(0, 0)}
unhashable type: 'list'
[(1, 2), (3, 4)]Adding (0, 1) a second time changes nothing, because the set already holds an equal tuple. The & operator gives the intersection of two sets. To deduplicate a list of lists, convert each inner list to a tuple first. The set comprehension does that in one pass.
Equality decides what counts as the same key
Dictionaries and sets use equality to decide whether two keys are the same. Tuples compare item by item, and Python considers 1, 1.0 and True equal. They also share a hash. That means keys that look different can collide.
d = {(1, 2): "a"}
d[(1.0, 2)] = "b"
print(d)
print(hash((1, 2)) == hash((1.0, 2)))
print((True, 2) in d)The output is:
{(1, 2): 'b'}
True
TrueThe second assignment did not add a key. It replaced the value under the existing key, and the dictionary kept the original key object (1, 2). This rarely matters in practice, but it can surprise you if you mix numeric types or booleans in keys. Convert the parts to one type before you build the key.
Tuple equality also depends on order and length. (1, 2) and (2, 1) are different keys. If you want a key where order does not matter, use frozenset({1, 2}) or sort the items before you build the tuple.
Hashable does not mean fully frozen
Hashability is checked only at the moment hash() is called, and it depends on the types of the items. A tuple can hold an object that is hashable but still changes internally. Custom classes are hashable by default, and they hash by identity unless you define __eq__ and __hash__.
class Token:
pass
a, b = Token(), Token()
table = {(a, 1): "x"}
print((a, 1) in table)
print((b, 1) in table)The output is:
True
FalseTwo Token objects are different keys even though they look the same, because the default hash and equality use object identity. This is safe, because mutating a Token does not change its identity hash. It is also easy to misread, so be deliberate about what you put in a key.
A real problem appears if you write a class that defines __eq__ and __hash__ from fields that you later modify. The hash would then change after the object is stored, and lookups would fail silently. If you define __hash__, base it only on fields that never change.
Common patterns
Sparse grids and coordinates
A dictionary keyed by (row, column) stores only the cells that matter. This is cheaper than a full list of lists when most cells are empty.
Memoization
A function with several arguments can cache results under a tuple of its arguments. The next example counts the routes across a grid when you can only move down or right.
cache = {}
def paths(r, c):
if r == 0 or c == 0:
return 1
key = (r, c)
if key not in cache:
cache[key] = paths(r - 1, c) + paths(r, c - 1)
return cache[key]
print(paths(16, 16))The output is 601080390. Without the cache, the function would repeat the same subproblems an enormous number of times. For simple cases, functools.lru_cache does this for you, and it also builds a hashable key from the arguments.
Grouping by several fields
A tuple of fields can serve as a composite key. Unpack the key in the loop so the names stay readable.
from collections import defaultdict
sales = [
("Oslo", 2025, 120),
("Oslo", 2025, 80),
("Bergen", 2025, 50),
("Oslo", 2026, 60),
]
totals = defaultdict(int)
for city, year, amount in sales:
totals[city, year] += amount
for (city, year), total in sorted(totals.items()):
print(city, year, total)The output is:
Bergen 2025 50
Oslo 2025 200
Oslo 2026 60The target (city, year), total is a nested unpacking pattern. It splits each key-value pair from items() and then splits the key.
Errors and pitfalls
- Looking up with a list.
grid[[2, 3]]raisesTypeError: unhashable type: 'list'. Convert withgrid[tuple(point)]. - Hidden mutable items. A tuple like
("config", ["a", "b"])cannot be a key. Replace the list with a tuple, or with afrozensetif order does not matter. - Converting nested data.
tuple(rows)only converts the outer list. For a list of lists, usetuple(tuple(row) for row in rows), or the result will still be unhashable. - Relying on hash values. String hashes vary between runs of the interpreter, so never store
hash()results or depend on them being the same across runs. - Relying on set order. A set has no guaranteed order. Use
sorted()when you need a stable output. - Float keys. Floating-point rounding means
(0.1 + 0.2, 1)does not equal(0.3, 1). Round values or use integers for keys.
Exercise
What happens with {(1, [2, 3]): "x"}, and how would you change the key so the dictionary can be built?
Show answer
It raises TypeError: unhashable type: 'list', because the tuple contains a list and a tuple is hashable only if every item is. Replace the list with a tuple, as in {(1, (2, 3)): "x"}. A frozenset would also work if the order of 2 and 3 does not matter.
Exercise
Given points = [[0, 1], [2, 3], [0, 1], [4, 5]], write one expression that gives the number of distinct points.
Show answer
len({tuple(p) for p in points}) returns 3. Each inner list is converted to a tuple so it can go into a set, and the set drops the duplicate (0, 1).
Exercise
After d = {(1, 2): "a"} and d[(True, 2)] = "b", how many keys does d have, and what is the value of d[(1, 2)]?
Show answer
One key and the value "b". True equals 1 and has the same hash, so (True, 2) is the same key as (1, 2). The assignment replaces the value and keeps the original key.