Inside Python's Dictionary: Hash Tables and Fast Lookups

An examination of how the Python dictionary works internally: hashing, the compact table, open addressing, resizing, insertion order and the pitfalls that follow from its design.

A green python coiled in neat, evenly spaced loops around a wooden branch, its head resting in the middle against a dark background.
Photo by Ali Jafarov on Unsplash

A dictionary with a million entries finds any key in roughly the same time as a dictionary with ten. This property supports a large part of the language: namespaces, instance attributes, keyword arguments and the keys of every JSON document handled by a program are all stored in dictionaries. The present article examines how CPython achieves it, from the hash function to the layout of the table, the resolution of collisions and the growth of the structure, and it identifies the pitfalls that follow from that design. The hash table is the secret weapon behind the dictionary, and understanding it explains both its speed and its occasional surprises.

The Hash Function

A hash table stores each entry at a position computed from its key, so that a lookup goes directly to that position instead of scanning every entry. The built-in function hash() produces the integer from which that position is derived.

print(hash(123))                  # Output: 123
print(hash(-1))                   # Output: -2
print(hash(1) == hash(1.0) == hash(True))  # Output: True
print(hash("hello") == hash("hello"))      # Output: True

Three properties appear in this example. Small integers hash to themselves, except -1, whose hash is -2 because the value -1 signals an error in the C implementation. Numbers that compare equal have equal hashes, which is required because the dictionary must treat them as the same key. Finally, a string always produces the same hash within one process, but not across processes: since Python 3.3, the hashes of str and bytes are randomized at start-up to protect servers against attacks that send many keys with colliding hashes, and PEP 456 adopted the SipHash family for them in Python 3.4. Running print(hash("hello")) twice in separate interpreters therefore prints two different numbers, unless the environment variable PYTHONHASHSEED fixes the seed.

Hashable, Not Merely Immutable

A key must be hashable, which means that its class defines __hash__ and that its hash never changes while it is stored in a dictionary. Immutability is a frequent guide, but it is not the exact rule, as the following example shows.

for key in ([1, 2], (1, [2]), (1, 2), frozenset({1, 2})):
    try:
        {key: "value"}
        print(type(key).__name__, "accepted")
    except TypeError as error:
        print(type(key).__name__, "rejected:", error)
# Output: list rejected: unhashable type: 'list'
# Output: tuple rejected: unhashable type: 'list'
# Output: tuple accepted
# Output: frozenset accepted

A tuple is hashable only if all of its elements are hashable, so the tuple that contains a list is rejected. Conversely, instances of user-defined classes are hashable by default, based on their identity, even though they are mutable. A class that defines __eq__ loses that default __hash__ and must define both methods consistently, as described in the article devoted to the data model.

From Hash to Slot

The hash is a large integer, while the table has a small number of slots, eight in a new dictionary. CPython keeps the number of slots at a power of two and takes the lowest bits of the hash as the index, hash & (size - 1), which gives the same result as hash % size for Python integers and is cheaper to compute.

The layout of the table changed in Python 3.6, which introduced a compact representation that uses 20 to 25 percent less memory. The table is split into two arrays:

  1. A sparse array of indices, with one small integer per slot, which is the part addressed by the hash.
  2. A dense array of entries, in which each entry stores the hash, the key and the value, appended in the order of insertion.

A lookup computes the slot, reads the index stored there and goes to the corresponding entry. The dense array also explains why dictionaries preserve insertion order: iteration simply traverses it. Order preservation was an implementation detail of CPython 3.6 and became part of the language specification in Python 3.7.

Collisions and Open Addressing

Two different keys can map to the same slot. CPython does not store a list per slot to hold the colliding keys; it uses open addressing, which means that the second key is placed in another free slot of the same array, chosen by a deterministic sequence. Many multiplayer shooters handle a similar situation in the same way: when a player respawns at a point that is already occupied, the game moves the player to another point chosen by a fixed rule, so that anyone who knows the rule can predict where the player will appear. In the dictionary, that rule depends on the whole hash, not only on its lowest bits, as the following simplified model of the CPython probing sequence shows.

def probe_sequence(hash_value, size, count):
    """Simplified model of the slots that CPython tries for one hash."""
    mask = size - 1
    perturb = hash_value & 0xFFFF_FFFF_FFFF_FFFF  # Treated as unsigned.
    slot = perturb & mask
    slots = [slot]
    for _ in range(count - 1):
        perturb >>= 5
        slot = (5 * slot + perturb + 1) & mask
        slots.append(slot)
    return slots

print(5 & 7, 37 & 7)              # Output: 5 5
print(probe_sequence(5, 8, 5))    # Output: [5, 2, 3, 0, 1]
print(probe_sequence(37, 8, 5))   # Output: [5, 3, 0, 1, 6]

Both hashes start at slot 5, but the higher bits of the second one, injected through the variable perturb, send it along a different path after the first collision. The comparison with respawn points ends at this point, because a lookup must also recognize the key it is looking for: at each occupied slot, CPython first checks whether the stored key is the same object, then whether the stored hash is equal, and only then calls __eq__. Most probes are therefore resolved by comparing two integers.

Expanding the Inventory: How the Table Grows

A table that fills up produces longer probing sequences, so CPython enlarges it before that happens. At most two thirds of the slots may be used; when an insertion would exceed that fraction, the dictionary allocates a larger table and reinserts every entry. The function sys.getsizeof makes these moments visible.

import sys

table = {}
last = sys.getsizeof(table)
print(0, last)
for number in range(30):
    table[number] = number
    size = sys.getsizeof(table)
    if size != last:
        print(len(table), size)
        last = size
# Output (CPython 3.12, 64-bit): 0 64, 1 224, 6 352, 11 632, 22 1168

for number in range(30):
    del table[number]
print(len(table), sys.getsizeof(table))  # Output (CPython 3.12, 64-bit): 0 1168

The empty dictionary allocates no table at all. The first insertion creates eight slots, of which five are usable, and the dictionary grows when the sixth, eleventh and twenty-second keys arrive, each time doubling the number of slots. Each resize costs time proportional to the number of entries, but it happens rarely enough that the average cost of an insertion remains constant. The second part of the example shows that deleting keys never shrinks the table, a detail that matters for dictionaries that grow large once and are then emptied, in line with the memory behaviour described in the article devoted to memory management.

Measuring Constant Time

The average cost of a lookup does not depend on the number of entries, whereas a search in a list grows linearly. The following measurement compares both for the last element.

import timeit

for size in (1_000, 100_000, 1_000_000):
    as_dict = dict.fromkeys(range(size))
    as_list = list(range(size))
    target = size - 1
    dict_time = min(timeit.repeat(lambda: target in as_dict, number=10_000, repeat=3)) / 10_000
    list_time = min(timeit.repeat(lambda: target in as_list, number=10, repeat=3)) / 10
    print(f"{size:>9,}: dict {dict_time * 1e9:.0f} ns, list {list_time * 1e6:.0f} us")
# Output (CPython 3.12, varies by machine):
#     1,000: dict 30 ns, list 4 us
#   100,000: dict 30 ns, list 359 us
# 1,000,000: dict 30 ns, list 3650 us

The dictionary answers in about 30 nanoseconds at every size, while the list takes a thousand times longer at one million elements. Constant time, however, is an average: it assumes that the hashes spread the keys across the table, an assumption that the following section shows to be fragile.

Pitfalls of Dictionaries

The design described above explains several behaviours that surprise even experienced programmers. Five pitfalls are distinguished, which are the following:

  1. Equal keys merge. 1, 1.0 and True are equal and have the same hash, so they are the same key; the dictionary keeps the first key object and the last value.
  2. NaN keys. A NaN is not equal to itself, so it can only be found again through the very same object, thanks to the identity check.
  3. Keys mutated after insertion. If the hash of a stored key changes, the entry stays in its old slot and can no longer be found, neither with the new value nor with the old one.
  4. Modification during iteration. Adding or removing keys while iterating over the dictionary raises RuntimeError.
  5. Poor hash functions. A __hash__ that returns the same value for many objects turns every lookup into a long probing sequence, and the cost degrades from constant to linear.

The first three pitfalls are reproduced in the following example.

table = {1: "int", True: "bool", 1.0: "float"}
print(table)  # Output: {1: 'float'}

nan = float("nan")
numbers = {nan: "stored"}
print(numbers[nan], float("nan") in numbers)  # Output: stored False

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

    def __hash__(self):
        return hash((self.x, self.y))

point = Point(1, 2)
places = {point: "here"}
point.x = 10
print(places.get(point), places.get(Point(1, 2)))  # Output: None None
print(list(places.values()))                       # Output: ['here']

The entry of the mutated point still exists, as the last line shows, but no key can reach it anymore. The fifth pitfall can be measured by building two dictionaries of 2,000 keys, one with a hash derived from the value and one with a constant hash.

import timeit

class Good:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)

class Constant(Good):
    def __hash__(self):
        return 42  # Every key collides with every other key.

for cls in (Good, Constant):
    seconds = min(timeit.repeat(lambda: {cls(i): i for i in range(2_000)}, number=3, repeat=3)) / 3
    print(f"{cls.__name__}: {seconds * 1000:.1f} ms")
# Output (CPython 3.12, varies by machine): Good: 0.3 ms, Constant: 69.0 ms

The constant hash makes the construction more than two hundred times slower, because every insertion compares the new key with all the previous ones. This is precisely the degradation that hash randomization prevents for strings received from untrusted sources.

Choosing the Right Structure

Consequently, the dictionary is the default choice whenever values must be found by a key, and its limits point to the alternatives. The following table summarizes the criteria.

Need Recommended structure
Find values by a hashable key dict
Test membership without values set or frozenset, built on the same kind of table
Composite keys A tuple of hashable values, or a frozen dataclass
Keys that must change after insertion Remove the entry, change the key and insert it again
Many objects with the same attributes Ordinary instances, which share their keys (PEP 412), or __slots__
Ordered data accessed by position list

The penultimate row refers to the key-sharing dictionaries of PEP 412, introduced in Python 3.3, which let instances of the same class share one array of keys; __slots__ removes the instance dictionary altogether, as examined in the article devoted to __slots__.

Conclusion

It is concluded that the speed of the Python dictionary comes from a hash table with open addressing: the hash selects a slot, a perturbed probing sequence resolves collisions, and the table grows before it is two thirds full. This magic rests on two conditions that the programmer controls, namely that keys keep a stable hash and that their hash function distributes them well; when either fails, the dictionary loses entries or degrades to linear time. The compact layout of Python 3.6 added insertion order and reduced memory without changing these principles. The method __missing__, which lets a subclass of dict decide what happens when a key is absent, is the natural continuation of this topic and is developed in a future article of this series.