dict and hashability

The dictionary is not just a data structure but the foundation of the language: namespaces, object attributes, keyword arguments and import all stand on it. From how it is built you can derive the guaranteed key order, the hash contract, and why a mutable object gets lost in a set.

L1 · 9 minL2 · 14 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Snippet A
d = {"a": 1, "b": 2, "c": 3}
del d["b"]
d["d"] = 4
print(list(d))
['a', 'c', 'd']
The new key went to the end, not into the freed slot.
Snippet B
class Point:
    def __init__(self, x): self.x = x
    def __eq__(self, other): return self.x == other.x

s = {Point(1)}
TypeError: unhashable type: 'Point'
We defined only equality — and lost the hashability that was there.
Snippet C
class Box:
    def __init__(self, x): self.items = [x]
    def __hash__(self): return hash(tuple(self.items))
    def __eq__(self, o): return self.items == o.items

b = Box(1)
s = {b}
print(b in s)
b.items.append(2)
print(b in s, any(x is b for x in s))
True
False True
The object is at once absent from the set and present in it.
Snippet D
print(hash(-1), hash(-2))
-2 -2
Two different numbers with the same hash — and that is no accident.

2Mechanism

From lesson 03 we know: searching a list is a scan, because a list knows only addresses. A dictionary solves the same problem differently — it computes where to look.

A hash table with open addressing. A key's position is taken from its hash; if the slot is occupied by another key, the probe moves along a deterministic sequence until a free or matching slot is found.

A compact layout (since 3.6). The data lives not in a sparse table but in two arrays: a dense array of entries in insertion order — hash, key, value — and an array of indices into that array, the size of the table. The indices take 1, 2, 4 or 8 bytes depending on the size of the dictionary.

Consequence 1 · key order is a side effect of compactness

Entries are appended to the dense array one after another, so iterating over a dictionary goes in insertion order. That was not the goal: the layout was invented to save memory, and the ordering came for free.

Snippet A shows that the order is precisely “insertion”, not “sorted”: a deletion marks an entry as empty but does not shift the rest, and a new key is appended at the end.

What follows is a story worth remembering in full, because it repeats throughout the language. In 3.6 the ordering was an implementation detail 🔧, and the release notes warned about that outright. By 3.7 too much code had come to lean on it, and it was made a language guarantee 🔒. An implementation turned into a specification — exactly because people started using it.

Consequence 2 · the hash contract, and what it forbids

For lookup to work, one rule is needed: equal objects must have equal hashes. The converse is not required — different objects may coincide in hash; that is a collision, and it is resolved by probing.

Hence snippet B. By defining __eq__ you changed the notion of equality — and the inherited __hash__, based on object identity, came to contradict it. Python does not let that happen: when __eq__ is defined without __hash__, it sets __hash__ = None, and the object stops being hashable.

print(Point.__hash__)
# → None

This is not a punishment but a protection against silent breakage: two equal objects with different hashes would end up in different buckets, and the dictionary would start to contain duplicates it cannot find itself.

Consequence 3 · mutability breaks lookup

The hash is computed at the moment of insertion and remembered in the entry. If the object then changes so that its hash becomes different, a lookup goes to the new bucket — while the object sits in the old one.

Snippet C: b in s returns False because we search by the new hash. Meanwhile the object is physically in the set and visible during iteration. It is not lost and not removed — it is unreachable by key, which is far more unpleasant.

This yields why a list cannot be made a key, although technically a hash could be computed from it: mutability means such a situation is bound to arise. Python preferred to forbid it up front. And from the same place come frozen=True on a dataclass that is going to be put into a set, and frozenset as a separate type.

Consequence 4 · collisions, and why hash(-1) is −2

Snippet D. In the C API the hash function returns -1 as an error indicator. So the real value −1 cannot be used, and the hash of −1 is shifted to −2. One collision built into the language for the sake of cheap error signalling.

Ordinary collisions are resolved by probing, and the probe sequence is chosen so as to involve the high bits of the hash as well, not only the low ones: otherwise keys with the same remainder would line up in one cluster. The practical meaning: a bad hash function in your class degrades the dictionary to linear search but does not break it.

Consequence 5 · string hash randomization

A string's hash depends on a random value chosen at process startup 🔧. That is why hash("x") gives different numbers in two different runs.

This was done after attacks in which an attacker picked keys with the same hash and turned request parsing quadratic. The side consequence matters in practice: a hash must not be stored between runs — not in a file, not in a cache, not as a sharding key. A stable hash needs an explicit algorithm from hashlib.

3Limits of the model

Where this stops holding

Order is guaranteed for dict but not for set: 🔒 for the former, 🕳 for the latter. A set uses a different layout, and its iteration order depends on the hashes and the history of insertions. It cannot be relied on, even though it looks stable within a run.

O(1) is amortized and on average. When the table fills beyond two thirds it grows and all the keys are rehashed; a single insertion at that moment costs O(n). And with a degenerate hash function lookup degrades to linear.

Index sizes and the moments of resizing are implementation details 🔧. The compact layout was introduced in 3.6, shared keys for instances in 3.3, storing values in the object's pre-header in 3.11. Behaviour and complexity are guaranteed, not bytes.

4Root

Root R2: a namespace is a dictionary. This makes it clear why the dictionary in Python has been optimized so aggressively: it is not one of the data structures but a load-bearing one. Every access to a global variable, every object attribute, every import, every call with keyword arguments goes through a dictionary.

The compact layout came out of exactly this role. Instances of one class have the same set of attribute names, so the keys can be stored once per class and the object can hold only an array of values — the very key sharing that in lesson 04 explained why property and the managed dict are built the way they are. The memory saving on objects and the ordering of dictionaries are two consequences of one optimization.

5Analogy

The compact layout is the CSR representation of a sparse matrix. There are two arrays there as well: a dense one with the non-zero values in a row, and an index one mapping a position into that dense array. The motivation is identical: a sparse structure spends memory on emptiness, so we keep the emptiness in a cheap index array and the data densely.

The consequence carries over too: just as iterating over the non-zero elements in CSR goes in the order they are stored, iterating over a dictionary goes in insertion order. In both cases ordering is a property of the layout, not a separate feature.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Dictionary order became a guarantee — why is there none for a set?

Because order in the dictionary appeared as a side effect of a useful optimization, and the set had no such optimization.

The compact layout of 3.6 split the dictionary into two parts: a dense array of entries in insertion order and a sparse array of indices into it. It was done for memory — the saving came out at 20–25%. Insertion order came for free: the entries lie in a row anyway.

A set is built differently — it is still one sparse table in which the position is determined by the hash. There is no dense array in insertion order there, and no reason to make one: there would be no saving, because there are no values.

print({"b": 1, "a": 2})           # → {'b': 1, 'a': 2}   insertion order 🔒
print({3, 1, 2})                  # → {1, 2, 3}          looks like sorting
print({"three", "one", "two"})    # → the order depends on the hashes and the salt

Small integers look “sorted” because hash(n) == n and they land at their own indices. That is a coincidence, not a property.

The main thing in this story is not the order but the precedent. In 3.6 it was an implementation detail 🔧 with an outright warning in the release notes; by 3.7 so much code had come to lean on it that it was made a guarantee 🔒. An implementation turned into a specification — exactly because people started using it. Deterministic destruction by reference count is travelling the same road now, and that one is precisely what does not get guaranteed.

Why does a string's hash() change between runs of a process?

It is a protection against denial of service, added in 3.3 after a public attack.

A dictionary degrades to linear search if all the keys fall into one bucket. Knowing the hash function, an attacker can pick thousands of strings with the same hash and send them as form fields or JSON keys — and processing a request goes from milliseconds to seconds. The vulnerability affected almost every language at once.

The answer: the hash of strings and bytes is salted with a random value, a fresh one for each run of the process.

$ python3 -c "print(hash('abc'))"
$ python3 -c "print(hash('abc'))"
# two different numbers

$ PYTHONHASHSEED=0 python3 -c "print(hash('abc'))"
$ PYTHONHASHSEED=0 python3 -c "print(hash('abc'))"
# identical

Practical consequences. A string's hash must not be saved to disk, put into a cache, used for sharding between processes or compared between runs — for that there is hashlib, which is stable by definition. And a test that checks the iteration order of a set of strings will be green exactly until the next run 🕳.

PYTHONHASHSEED=0 turns the salt off — sometimes needed for reproducible debugging, but in production it brings the vulnerability back.

Why can a list not be made a key, if its contents could be hashed?

They could be — exactly once. The problem is the second time.

The hash contract has two parts, and the second matters more than the first: equal objects have equal hashes, and the hash does not change over the object's lifetime. A dictionary remembers which bucket it put a key into. If the contents of the list change, so does its hash — while the entry stays in the old bucket.

class Sneaky(list):
    __hash__ = lambda self: hash(tuple(self))   # “let us hash it anyway”

d = {Sneaky([i]): i for i in range(200)}
k = Sneaky([500])
d[k] = "value"

k.append(1)                                     # the key changed in place
print(d[k])
# → KeyError: [500, 1]        not found even by the very same object
print("value" in d.values(), len(d))
# → True 201                  the entry is in place and unreachable

The entry is not lost and not damaged — it simply will never be found again. No exception at the moment of breakage, no way to detect it. This is the worst kind of error: silent and delayed.

On a small dictionary the same code may work by accident: the index array is short, the old and the new hash fall into the same cell, and the match is found by identity. That makes the error even worse — it shows up as the data grows.

That is why the mutable built-in types are forcibly declared unhashable — __hash__ = None. Not because a hash cannot be computed, but because the contract cannot be kept. If you need a key made of a sequence — tuple; a key made of a set — frozenset; a key made of your own class — implement __hash__ only over the fields that do not change.

The compact dictionary gave both memory and order — why was it not done earlier?

Because the idea was not obvious, and the price of a mistake in the dictionary is the performance of the whole language.

The dictionary in Python is not a data structure from the standard library but a load-bearing one: a module's namespace, an instance's __dict__, a class's method table, keyword arguments — all of these are dictionaries. Any change touches every program, so people go in there carefully and with measurements.

The 3.6 layout was proposed by Raymond Hettinger in 2012, and it matured for four years before release. The idea: instead of one sparse table of entries, a dense array of entries plus a separate sparse array of small indices. The sparse part now stores not 24-byte entries but indices of 1, 2, 4 or 8 bytes depending on the size of the dictionary.

import sys
d = {}
prev = -1
for i in range(40):
    if sys.getsizeof(d) != prev:
        prev = sys.getsizeof(d); print(len(d), prev)
    d[i] = i

This is not the only optimization of the dictionary, and the others came late too: shared keys for instances of one class (PEP 412, version 3.3), moving instance values into the object's preamble (3.11), a version counter for the inline caches of LOAD_GLOBAL (3.11). All of them are 🔧 and all of them changed the layout.

A conclusion useful beyond the dictionary: in a mature language the basic structures keep being rewritten for decades, and any test that leans on their bytes is a time bomb.

Bottom line. A dictionary is a hash table with open addressing and a compact layout of two arrays: a dense one with entries in insertion order and an index one. Hence key order, which was first a side effect of saving memory and since 3.7 has been a language guarantee. The contract “equal objects — equal hashes” is protected automatically: define __eq__ without __hash__ and you lose hashability, because otherwise the dictionary would start to contain duplicates it cannot find itself. The hash is remembered at insertion, so a mutable object stays in the set after mutation but becomes unreachable by key — and therefore only something immutable can be a key. String hashes are randomized at process startup, so they must not be stored between runs.
From here on — optional
counterfactualC++ unordered_map, Java, GoChaining with stable references versus open addressing; Go randomizes the order on purpose
Counterfactual · the same questions elsewhere

Java's HashMap uses chaining: a bucket holds a linked list that turns into a tree when the chain gets long. More resistant to bad hashes, but every node is a separate object — that is, indirection and memory. Python chose open addressing: everything in two arrays, better for the cache, worse with degenerate hashes.

C++ std::unordered_map is built like Java's: chains in buckets, every node a separate allocation. The standard in effect requires references to elements to stay stable on insertion, and that closes the road to open addressing — with it elements move. Python made no such commitment and could therefore choose a layout that is friends with the cache: two dense arrays instead of a graph of nodes. The price is that a reference to a dictionary entry lives only until the next resize, and that is exactly why mutating a dictionary while iterating over it is forbidden 🔒.

Go left the iteration order of a map not merely unguaranteed but deliberately random: the runtime starts from a different place every time so that nobody can lean on the order. The direct opposite of Python's decision — where the order first arose by accident and then became a promise.

Two languages, one situation — “an order technically exists” — and two opposite conclusions: pin it down or break it on purpose.

🐛 bugA key that is changed after insertionThe hash is remembered at insertion — the entry is not overwritten but duplicated, and becomes unreachable
🐛 The bug that passes review

A cache keyed by an object that is later extended. Entries start to duplicate, and the old ones become unreachable.

@dataclass
class Filter:
    field: str
    values: list          # ← a mutable field

    def __hash__(self):
        return hash((self.field, tuple(self.values)))

cache = {}
f = Filter("status", ["new"])
cache[f] = run_query(f)

f.values.append("done")   # somewhere further down the code
cache[f] = run_query(f)   # we think we have overwritten it

Review sees a correct __hash__ — a tuple, just as taught. But consequence 3 says: the hash was computed at insertion and remembered. After append the object is looked up by a new hash, is not found, and the second line does not overwrite the entry but adds a second one. The dictionary now has two keys that are considered equal, and the first of them is unreachable.

The symptoms are nasty: the cache grows, there are no hits, and len(cache) is larger than the number of unique filters. And all of it with no exception and no warning.

The cure follows from the mechanism: only something that does not change can be a key. Either @dataclass(frozen=True) and a tuple instead of a list in the field, or compute the key explicitly — as a string or a tuple — and do not make the object itself hashable. The second is often more honest: a cache key and a domain object are different entities, and there is no need to mix them.

⚡ 3×A tuple instead of a glued string0.087 s to build a string key versus 0.030 s for a tuple
⚡ A composite key at a third of the cost

The classic technique “glue the fields into a string and use that as the key” costs more than it seems.

cache[f"{user_id}:{region}"] = value      # how it is usually written
cache[(user_id, region)]     = value      # cheaper this way
500,000 lookupstime
a ready-made string key0.022 s
a tuple key0.030 s
a string built on every lookup0.087 s

The lookup by string itself is slightly faster than by tuple — a string's hash is cached in the header (lesson 02), a tuple's is computed every time. But in real code the string has to be built, and that is creating a new object, formatting, and computing a hash from scratch. Hence the threefold difference from the tuple, which simply refers to objects that already exist.

When it is noticeable: a hot path with hundreds of thousands of lookups — routing, deduplication, metric aggregation. When it is not: rare lookups, where readability matters more. And a separate advantage of the tuple besides speed: it does not break if a field happens to contain a colon.

💻 terminalCheck it in the REPLFour snippets plus {1, 1.0, True}, nan as a key, and order in a set

Check it yourself

Run the four snippets and check them against your prediction. Then:

{1, 1.0, True}
# How many elements, and why?

d = {}
d[float("nan")] = 1
d[float("nan")] = 2
len(d)
# And now: n = float("nan"); d2 = {n: 1}; n in d2 — what will it return?

class C:
    __slots__ = ()
    def __eq__(self, o): return True
# Can you put C() into a set? What needs to be added?

# Without code: why does a set not guarantee order
# if a dict does, and both are hash tables?

The second question is about the fact that a dictionary lookup first compares by identity and only then by equality; nan is not equal to itself, but it is itself.

source_HashedSeq in lru_cacheThree lines so that the hash of a cache key is computed once

Where it lives in real code

Lib/functools.py, the _HashedSeq class. Three lines inside lru_cache: a wrapper over the tuple of arguments that computes the hash once in the constructor and returns the saved one from __hash__.

Notice why this is needed. The cache key is looked up in a dictionary on every call, and without the wrapper the hash of the argument tuple would be recomputed every time — which is a walk over all its elements. The standard library here literally pays with one class so that consequence 2 runs once rather than on every lookup.

The second place is Lib/collections/__init__.py, OrderedDict. It stayed in the library after the ordinary dictionary became ordered, and the documentation honestly explains how it still differs: order-sensitive equality and the move_to_end method. A good example of a language guarantee not abolishing a specialized type but narrowing its field of use.

L2Layout, growth and the price of collisionsGrowth jumps, probing with perturb, shared keys

From L1 you know about the two arrays. Here: how they grow and what measurements show.

Sizes in practice:

sys.getsizeof({})                    64
after 1 key                          224
after 6                              352
after 11                             632
after 22                            1168

An empty dictionary is just the header; the table is not allocated at all. The first insertion allocates a table of eight slots at once. From then on growth happens at roughly two-thirds full: the table doubles, all the entries are moved, the indices are recomputed. The two-thirds threshold was chosen as a trade between memory and probe length — at denser filling collisions become more frequent non-linearly.

The probe sequence in CPython is neither linear nor quadratic but this: i = (i * 5 + 1 + perturb) & mask, where perturb starts as the full hash and is shifted right on every step. The point is for the first probes to involve the high bits of the hash: if only the low ones were taken, keys differing in the high bits would cluster in one place.

Shared keys. For the attribute dictionaries of instances the key table is moved to the class, and the object holds only an array of values. Hence the saving from lesson 04: a thousand objects of one class do not pay a thousand times for identical field names.

What is worth knowing how to measure: sys.getsizeof on a dictionary grows in jumps — they show the moments of resizing; if you know how many keys there will be, dict has no way to reserve room in advance, but there is a workaround through creating it from a ready iterable whose size is known.

L3Where this is in the CPython sourcesdictobject.c: the file header, lookdict_split; setobject.c; PEP 412

Tag v3.11.15.

  • Objects/dictobject.c, the file header — a large comment describing the compact layout and the motivation. It reads in ten minutes and replaces half of this lesson.
  • In the same file, lookdict_index and lookdict_split — probing and the path for shared keys.
  • Objects/setobject.c — a different layout, with no dense array; hence the absence of an order guarantee.
  • PEP 412 — shared keys; the motivation is written in megabytes on real applications.
connectionsWhere this leadsL03, L04, L06 · the contrast with chaining and with randomization in Go

Connections

root R2 · Attributes are resolved at runtime, a namespace is a dict
← foundation L03 · Containers — why in on a list is linear and here it is not
← foundation L04 · obj.x, end to end — the shared keys discussed there are built here
↔ contrast Chaining in Java's HashMap versus open addressing: resistance to bad hashes versus locality
↔ contrast Go deliberately randomizes the iteration order of a map — the opposite conclusion from the same situation
→ next L06 · Classes — a class body is a dictionary, and the MRO determines the order in which they are searched
not covered here Cryptographic hashes and stable sharding — that is hashlib, a different problem
readingFurther readingThe dictobject.c header 🟥 · __hash__ 🟧 · PEP 412 🟦

Further reading

Written by · The Python Canon