Dictionaries and sets
How dict and set find a key in constant time on average: hashing, open addressing with CPython's probe rule, the compact insertion-ordered layout, the load factor and resizing, hashable keys, the worst case, set algebra, Counter and defaultdict.
Finding by key
The topic Lists and tuples ended on a limit of the list. It finds an item by position in , but finding an item by its value, x in xs, compares against the items one by one: .
Here is where that hurts. Count the words of a small corpus with a list of [word, count] pairs:
corpus = "the cat sat on the mat the end".split()
pairs = [] # [word, count] pairs
for w in corpus:
for p in pairs:
if p[0] == w: # compare with each stored word
p[1] += 1
break
else: # no pair matched: a new word
pairs.append([w, 1])
print(pairs)[['the', 3], ['cat', 1], ['sat', 1], ['on', 1], ['mat', 1], ['end', 1]]It works, but every word of the corpus walks the list of words seen so far. With a vocabulary of distinct words, each step costs up to comparisons.
A dictionary, dict, maps keys to values and finds a key without walking anything. The same counter:
corpus = "the cat sat on the mat the end".split()
counts = {}
for w in corpus:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
print(counts)
print(counts["the"], "mat" in counts, len(counts)){'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}
3 True 6counts[w] reads or writes the value of key w, and w in counts asks whether the key is there. A set is the same structure with keys and no values. How fast is it? On one Apple M1 with CPython 3.14.7, x in xs for the last of integers in a list took about 840,000 ns. The same test on a set took about 35 ns, and still about 35 ns with items, where the list took about 8 ms. Your timings will differ; the gap will not.
Both dict and set are hash tables. This topic shows how a hash table finds a key, how CPython lays it out in memory, when it grows, which objects can be keys, and when the speed is lost.
From a key to a slot
A hash table turns the key itself into a position. A hash function maps the key to an integer, its hash, and the hash picks a slot of the table. A lookup computes the same slot and checks one or two candidates instead of all keys.
Python's hash function is hash(obj). It obeys one rule: if a == b, then hash(a) == hash(b). The reverse need not hold. Two different keys may share a hash, and that is a collision.
print(hash(3), hash(-1), hash(2**61 - 1), hash(2**61))
print(hash(1) == hash(1.0) == hash(True))3 -2 0 1
TrueAn int hashes to its value modulo the prime . So small integers hash to themselves, and hashes to 1. The one exception is : CPython's C code uses to signal an error, so hash(-1) is . A float or a bool equal to an integer hashes like that integer, which keeps the rule across numeric types.
Strings are hashed with SipHash-1-3, a function with a secret key. The key is chosen at random each time the interpreter starts. So the same string gets a different hash in every run:
$ python3.14 -c 'print(hash("the"))'
-3780534165771992150
$ python3.14 -c 'print(hash("the"))'
5344889949205395003Within one run the hash never changes, and that is all a table needs. Setting the environment variable PYTHONHASHSEED=0 fixes the key, so runs repeat.
From the hash to a slot: a table has slots, and in CPython is always a power of two, . The first slot tried is hash(key) & (m - 1). Here & is bitwise AND, and & (m - 1) keeps the lowest bits of the hash, which equals hash(key) % m for a non-negative hash. A new dict has slots, so the first slot is the hash's low 3 bits:
d = {17: "a", 3: "b", 9: "c"}
for k in d:
print(k, hash(k) & 7)17 1
3 3
9 1Keys 17 and 9 both start at slot 1. The table must put one of them elsewhere, and the lookup d[9] must find it there.
Open addressing
CPython resolves collisions by open addressing. Every key lives in the table itself. A key whose slot is taken tries other slots in a fixed order, its probe sequence, until it finds its own key (lookup succeeds) or an empty slot (the key is absent, or an insertion can go there).
For a table of slots and a hash , CPython's sequence is
with . Here shifts right by 5 bits, that is, floor division by 32. The perturb term mixes the higher bits of the hash into the first steps, so keys that agree in their low bits still take different paths. Once it reaches 0, only is left, and in a power-of-two table that recurrence visits every slot once before repeating. So an empty slot is always found.
The rule, replayed in Python:
def probe_slots(h, m, count):
"""The first `count` slots CPython tries for hash h in a table of m slots."""
slots, j, perturb = [], h & (m - 1), h
for _ in range(count):
slots.append(j)
perturb >>= 5
j = (5 * j + 1 + perturb) & (m - 1)
return slots
print(probe_slots(9, 8, 4))
print(probe_slots(0, 8, 9))[1, 6, 7, 4]
[0, 1, 6, 7, 4, 5, 2, 3, 0]The second line shows hash 0 visiting all 8 slots before it returns to slot 0.
Each slot on the way is checked in three steps of rising cost: is it the very same object (is)? Is the stored hash equal? Only then: is stored == key? Comparing hashes first skips most calls to ==, which can be slow for long strings.
Now trace d[9] in {17: "a", 3: "b", 9: "c"}. The first slot is . Slot 1 holds key 17 with stored hash 17, not 9, so the keys cannot be equal and == is never called. Next, , so the next slot is . Slot 6 holds key 9, the same object, and the lookup returns 'c'. The insertion of 9 walked the same path and stopped at slot 6, the first empty one.
Two arrays and the order
The table from the trace is really two arrays. Since CPython 3.6 a dict keeps its entries, each a triple of hash, key and value (24 bytes), in a dense array in insertion order. The hash table proper is a separate array of small integers, the indices. Each slot holds an entry number, or for empty. Reading the memory of {17: "a", 3: "b", 9: "c"} on CPython 3.14.7 gives exactly the slots of the trace:
indices: [-1, 0, -1, 1, -1, -1, 2, -1]
entries: 0 → (17, 'a'), 1 → (3, 'b'), 2 → (9, 'c')Why two arrays? A table is never more than two-thirds full (next block), so many slots are empty. Before 3.6 every slot was a whole 24-byte entry, and a third of the memory held nothing. Now only the indices are sparse, and they take 1 byte each in tables of up to 128 slots. For the old layout took bytes. The new one takes 8 bytes of indices and room for 5 entries, : 128 in all.
The layout also gives an order. Iterating over a dict walks the entry array, so keys come out in the order they were first inserted. Since Python 3.7 the language guarantees it. Changing a value keeps the key's place. Deleting a key empties its entry and marks its slot as a dummy, not as empty, because later lookups must keep probing past it. Inserting the key again appends a new entry at the end:
counts = {"the": 3, "cat": 1, "sat": 1}
counts["the"] = 4 # new value, same place
print(list(counts))
del counts["cat"]
counts["cat"] = 1 # back in, at the end
print(counts)['the', 'cat', 'sat']
{'the': 4, 'sat': 1, 'cat': 1}Sets do not use this layout. A set stores its keys directly in a sparse table and promises no order at all.
The load factor
The load factor of a table is : keys in slots. CPython lets a dict of slots hold at most entries, so . The insertion that finds no room builds a new table whose size is the smallest power of two at least , with the number of keys stored, and reinserts every key.
Start from 8 slots, 5 usable. The sixth key asks for slots, so the table grows to 16, with 10 usable. The eleventh asks for 30, so 32, with 21 usable. sys.getsizeof shows the jumps:
import sys
d, last = {}, sys.getsizeof({})
for k in range(1, 30):
d[k] = None
size = sys.getsizeof(d)
if size != last:
print(f"key {k}: {last} -> {size} bytes")
last = sizekey 1: 64 -> 224 bytes
key 6: 224 -> 352 bytes
key 11: 352 -> 632 bytes
key 22: 632 -> 1168 bytesThe sizes are those of a 64-bit build. The empty dict has no table yet, and the first key creates one of 8 slots. Each resize doubles , so the argument for append from Lists and tuples applies: insertions reinsert fewer than keys in all, which is amortized per insertion.
Why cap at all? Assume every probe lands on a random slot, independent of the others, an idealization of a good hash. A probe then hits an occupied slot with probability . A search for an absent key stops at the first empty slot, so it takes exactly probes with probability . The mean of this distribution is
At most three probes on average, whatever is. A simulation with a fixed seed gives 2.01, 2.99 and 9.99 probes at load factors 0.5, 2/3 and 0.9, against 2, 3 and 10. The last number shows what the cap prevents: as , the cost explodes.
Hashable keys and the worst case
Everything so far rests on a contract: equal keys have equal hashes, and a key's hash never changes while it is in a table. An object that keeps the contract is hashable. Python cannot check it, so the built-in types play safe.
Suppose a key could change after insertion. Its entry stays in the slot its old hash chose, and every later lookup computes the new hash and probes somewhere else. The key is in the dict, yet no lookup can ever find it. That is why the mutable built-ins, list, dict and set, are unhashable: an error at insertion beats a key that silently vanishes. A tuple is hashable when everything inside it is, and frozenset is the immutable, hashable set:
bigrams = {("the", "cat"): 1, ("cat", "sat"): 1} # tuples of str: hashable
seen = {frozenset({"the", "cat"}): True} # a frozen set: hashable
print(frozenset({"cat", "the"}) in seen)
vocab = {["the", "cat"]: 0} # a list: TypeErrorTrue
Traceback (most recent call last):
...
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')Equal keys are one key. 1 == 1.0 == True, and their hashes agree, so a dict treats them as the same key. How our own classes keep the contract comes in the topic The data model.
The constant cost is an average over keys that hash well. If all keys share one hash, every insertion probes past all earlier keys. Multiples of all hash to 0, so they make the worst case without any tricks. dict.fromkeys(keys) builds a dict with those keys:
import timeit
M = 2**61 - 1
good = list(range(2000))
bad = []
for k in range(2000):
bad.append(M * k) # hash(M * k) is 0 for every k
for name, keys in (("good", good), ("bad", bad)):
t = min(timeit.repeat(lambda: dict.fromkeys(keys), number=1, repeat=5))
print(f"{name}: {t / len(keys) * 1e9:,.0f} ns per key")good: 13 ns per key
bad: 13,758 ns per keyThese timings are from one M1 and will differ on your machine. Doubling the number of colliding keys roughly quadruples the total time.
| Operation | Average | Worst case |
|---|---|---|
d[k], k in d, d[k] = v, del d[k] |
||
| building a dict of keys |
An attacker who sends a web server thousands of colliding strings could make one request cost seconds of CPU. This "hash flooding" is why string hashes have used a random secret key by default since Python 3.3.
Sets
A set is an unordered collection of distinct hashable objects: a hash table of keys without values. Membership, add and discard cost on average. The operators of set algebra build new sets: | union, & intersection, - difference, ^ symmetric difference (in exactly one of the two). <= tests for a subset. Note that {} is an empty dict; the empty set is set().
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b, a & b, a - b, a ^ b)
print({3, 4} <= a, type({}), set())
words = ["to", "be", "or", "not", "to", "be"]
print(len(set(words)), list(dict.fromkeys(words))){1, 2, 3, 4, 5} {3, 4} {1, 2} {1, 2, 5}
True <class 'dict'> set()
4 ['to', 'be', 'or', 'not']The small integers print in order only because they hash to themselves and land in consecutive slots. A set of strings prints in a different order in every run, since string hashes change between runs. That is why the next example sorts before printing. set(words) removes duplicates and forgets the order. dict.fromkeys(words) removes them and keeps the order of first appearance, because a dict is ordered.
Sets answer questions about vocabularies directly. Which test words did the model never see in training?
train = set("the cat sat on the mat".split())
test = set("the dog sat on the log".split())
print(sorted(test - train)) # words never seen in training
print(sorted(train & test), len(train | test))['dog', 'log']
['on', 'sat', 'the'] 7a & b loops over the smaller set and looks each element up in the larger one, so it costs .
Counting and grouping
Two patterns come up constantly: counting how often each key occurs, and collecting items into groups by key. counts[w] for a missing key raises KeyError. A plain dict avoids it with d.get(k, default), which returns the default instead. The module collections has a ready type for each pattern:
from collections import Counter, defaultdict
words = "the cat sat on the mat the end".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1 # 0 for a word not seen yet
c = Counter(words)
print(c == counts, c.most_common(2), c["dog"])
by_len = defaultdict(list)
for w in words:
by_len[len(w)].append(w) # a new key starts as []
print(dict(by_len))True [('the', 3), ('cat', 1)] 0
{3: ['the', 'cat', 'sat', 'the', 'mat', 'the', 'end'], 2: ['on']}A Counter is a dict whose missing keys count 0 instead of raising KeyError. most_common(k) returns the largest counts, ties in first-seen order. A defaultdict(list) calls list() to create the value of a key the first time the key is used, so by_len[3].append(w) needs no check. Its trap is the reverse of KeyError: merely reading by_len[7] inserts the key 7 with an empty list.
Every NLP pipeline starts with such a dict. A vocabulary maps each token to an integer id:
words = "the cat sat on the mat the end".split()
vocab = {}
for w in words:
if w not in vocab:
vocab[w] = len(vocab) # the next free id
print(vocab)
print(vocab["mat"], vocab.get("dog")){'the': 0, 'cat': 1, 'sat': 2, 'on': 3, 'mat': 4, 'end': 5}
4 NoneA bag-of-words vector is a Counter of tokens, metrics are collected in dicts, and a PyTorch model's state_dict() is a dict from parameter names to tensors.
Every dict in this topic was built by a loop: a for over the words, one insertion per pass. The same for walks lists, strings, ranges and dict keys, though each is laid out differently in memory. The next topic, Iteration, comprehensions and generators, shows the small protocol that lets one for walk all of them. It then builds the shorter forms for making lists, dicts and sets, and the generators that produce items only when asked.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.