Sub topic 8
Frozensets and Tuples as Composite Keys
What you should know first
This chapter assumes you already know three things from earlier chapters:
- Dict keys and set elements must be hashable.
- Tuples are immutable, ordered sequences.
- Sets support union, intersection, and difference.
Here the focus is practical. Sometimes the thing you want to look up is not one value but a combination of values, such as a grid position, a pair of cities, or a group of tags. You will see how tuples and frozensets turn such combinations into valid keys, and where each one fails.
The problem: a key made of several parts
Suppose you store the contents of a grid. Each cell is identified by a row and a column. You could nest dicts (grid[row][col]), but a single dict with one key per cell is usually simpler. The key has to be one object, and it has to be hashable. A list like [2, 3] is not hashable, so you need an immutable container that holds the parts together.
Python offers two built-in choices:
- A tuple keeps the parts in order and keeps duplicates.
- A frozenset is an immutable set. It ignores order and duplicates.
The right choice depends on what makes two keys "the same" in your problem.
Tuples as composite keys
A tuple is hashable when every item inside it is hashable. Python computes the tuple's hash from the hashes of its items, and two tuples are equal when their items are equal in order.
grid = {}
grid[(0, 0)] = "start"
grid[(2, 3)] = "wall"
grid[1, 1] = "path" # the parentheses are optional in a subscript
print(grid[(1, 1)]) # path
print(grid.get((5, 5), "empty")) # empty
print((2, 3) in grid) # True
print((3, 2) in grid) # False, because order mattersThe line grid[1, 1] works because 1, 1 already builds a tuple. Many programmers still write the parentheses so the intent is obvious.
Hashing looks inside the tuple
A tuple is only as hashable as its contents. If one item is a list, the whole tuple is unhashable. Python reports the error when it tries to compute the hash, not when you build the tuple.
def is_hashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
print(is_hashable((1, 2))) # True
print(is_hashable((1, [2]))) # False
print(is_hashable((1, (2, 3)))) # True, nested tuples are fine
print(is_hashable(frozenset({1, 2}))) # True
print(is_hashable({1, 2})) # False
cells = {}
try:
cells[(0, [1])] = "x"
except TypeError as e:
print(e) # unhashable type: 'list'The tuple (1, [2]) is a valid tuple. It simply cannot be used as a key. This is the "shallow immutability" problem from the pitfalls chapter, seen from the other side: a tuple that holds a mutable object is not hashable, so Python refuses to use it as a key.
Turning nested lists into a key
Sometimes your data starts as a list of lists, for example a game board. To use it as a key, convert every level to a tuple.
board = [[1, 0], [0, 1]]
key = tuple(tuple(row) for row in board)
seen = {key}
board[0][0] = 9 # change the original board
print(key) # ((1, 0), (0, 1))
print(key in seen) # True, the key is an independent snapshotThe conversion copies the values, so later changes to board do not affect the stored key. That is usually what you want. A key must not change after you insert it, or the dict will look for it in the wrong place.
Equal values hash equally, even across types
Dict lookup uses hash and equality. Because 1 == 1.0 == True in Python, and those values have equal hashes, tuples containing them match each other.
d = {(1, 2): "a"}
print(d[(1.0, 2)]) # a
print(d[(True, 2)]) # aThis rarely causes trouble with coordinates. It can surprise you when a tuple mixes flags and numbers. If True and 1 mean different things in your key, add a distinguishing item, such as a label string.
Tuples as arguments to cached functions
functools.lru_cache stores results in a dict keyed by the call's arguments. The arguments therefore have to be hashable, and tuples fit naturally.
from functools import lru_cache
@lru_cache(maxsize=None)
def paths(row, col):
if row == 0 or col == 0:
return 1
return paths(row - 1, col) + paths(row, col - 1)
print(paths(3, 3)) # 20Passing a list to a function wrapped this way raises TypeError: unhashable type: 'list'. Convert the list to a tuple at the call site.
Frozensets
A frozenset is the immutable counterpart of a set. You build it from any iterable, and it supports the same read-only operations: membership, union, intersection, difference, and subset tests. It has no add, remove, or update methods.
fs = frozenset([3, 1, 3, 2])
print(len(fs)) # 3
print(sorted(fs)) # [1, 2, 3]
print(sorted(fs | {9})) # [1, 2, 3, 9]
print(type(fs & {1, 2})) # <class 'frozenset'>
try:
fs.add(4)
except AttributeError as e:
print(e) # 'frozenset' object has no attribute 'add'Two details are worth remembering.
- A frozenset equals a set with the same elements.
frozenset({1, 2}) == {2, 1}isTrue. - The result of an operation takes the type of the left operand.
frozenset({1}) | {2}is a frozenset, while{2} | frozenset({1})is a set.
The elements of a frozenset must themselves be hashable. A frozenset cannot contain a list or a set, but it can contain tuples and other frozensets.
Keys where order does not matter
A tuple key ("Oslo", "Bergen") is a different key from ("Bergen", "Oslo"). If the distance between two cities is the same in both directions, you would need to store it twice or sort the pair every time. A frozenset key makes the order irrelevant.
distances = {
frozenset({"Oslo", "Bergen"}): 463,
frozenset({"Oslo", "Trondheim"}): 392,
}
def distance(a, b):
return distances[frozenset({a, b})]
print(distance("Bergen", "Oslo")) # 463
print(distance("Oslo", "Bergen")) # 463
tuple_keys = {("Oslo", "Bergen"): 463}
try:
tuple_keys[("Bergen", "Oslo")]
except KeyError as e:
print("missing", e) # missing ('Bergen', 'Oslo')The same idea removes duplicates among unordered pairs. A set comprehension of frozensets collapses ("a", "b") and ("b", "a") into one element.
pairs = [("a", "b"), ("b", "a"), ("a", "c"), ("c", "a"), ("a", "b")]
unique = {frozenset(p) for p in pairs}
print(len(unique)) # 2A set cannot hold another set, because sets are unhashable. A set of frozensets is the standard way to represent "a collection of groups".
What a frozenset key throws away
Building a frozenset discards order and duplicates. That is the point, but it can hide information.
frozenset({"Oslo", "Oslo"})has one element. A "route" from a city to itself becomes a one-element key, which is easy to miss in code that expects two items.frozenset([2, 2, 5])equalsfrozenset([2, 5]). If the count of each item matters, a frozenset key merges cases that should stay separate.
When order does not matter but counts do, sort the items and use a tuple.
hand1 = [2, 2, 5]
hand2 = [5, 2, 2]
print(frozenset(hand1) == frozenset(hand2)) # True
print(frozenset([2, 5]) == frozenset(hand1)) # True, the count of 2 is lost
print(tuple(sorted(hand1)) == tuple(sorted(hand2))) # True
print(tuple(sorted([2, 5])) == tuple(sorted(hand1))) # FalseSorting requires the items to be comparable with each other. A tuple of mixed types such as (1, "a") cannot be sorted in Python 3. For counts of arbitrary hashable items, a later chapter introduces collections.Counter, which you can convert with frozenset(counter.items()).
Choosing between the key types
| Key type | Order matters | Duplicates kept | Items must be | Typical use |
|---|---|---|---|---|
| Tuple | Yes | Yes | Hashable | Coordinates, records, function arguments |
| Sorted tuple | No | Yes | Hashable and sortable | Multisets, canonical form of a group |
| Frozenset | No | No | Hashable | Unordered pairs, sets of tags, graph edges |
The diagram below turns the table into questions you can ask in order.
Edge cases and costs
Mutable objects hiding in a key
A tuple whose items are all hashable is safe. The danger comes from objects that are hashable but still mutable, such as instances of your own classes that define __hash__ from changing fields. If such an object changes after you store it, the dict may no longer find it.
Built-in tuples and frozensets of built-in immutable values cannot have this problem. The risk appears only with custom classes.
Cost of hashing
Looking up a key means hashing it first. For a tuple, the hash depends on every item, so a long tuple costs more than a short one, and a tuple of tuples costs more still. In CPython, a frozenset computes its hash once and stores it, so repeated lookups with the same frozenset object are cheap. Building a new frozenset for every lookup, as distance does above, costs time proportional to the number of elements each call. For two-element keys this is negligible. For large keys, build the key once and reuse it.
Containers that are not keys
Two common mistakes come up repeatedly:
- Using a set as a dict key raises
TypeError: unhashable type: 'set'. Wrap it withfrozenset(...). - Using a frozenset as a replacement for a list when you need order. Frozensets have no index, so
fs[0]raisesTypeError. Use a tuple.
When a key needs names
A tuple key such as (row, col, layer) is compact but easy to misread. If a composite key appears in many places, a collections.namedtuple gives each part a name while remaining hashable and equal to a plain tuple with the same items. The final chapter covers it.
Summary of rules
- A key must be hashable, and a container is hashable only when everything inside it is.
- Use a tuple when order matters or duplicates carry meaning.
- Use a frozenset when only membership matters.
- Use a sorted tuple when order does not matter but counts do.
- Convert mutable input to an immutable copy before using it as a key.
Exercise
You store the number of messages exchanged between pairs of users in a dict. Messages from "ana" to "ben" and from "ben" to "ana" should be counted together. Write the key expression for a pair (a, b), and explain what goes wrong if a user messages themselves.
Show answer
Use frozenset((a, b)) as the key, for example counts[frozenset((a, b))] = counts.get(frozenset((a, b)), 0) + 1. Both directions produce the same key because a frozenset ignores order. If a == b, the frozenset has only one element, so the key does not have two members. Code that unpacks the key into two names, or that checks len(key) == 2, would fail for self-messages, so handle that case explicitly.
Exercise
What does this code print, and why? Fix it so the last line prints True. seen = set() row = [1, 2] seen.add(row) print(row in seen)
Show answer
The seen.add(row) line raises TypeError: unhashable type: 'list', so nothing after it runs. A list is mutable and has no hash. Convert it to a tuple before adding and before testing: seen.add(tuple(row)) and print(tuple(row) in seen). The last line then prints True.