Sub topic 13
How hash tables give fast lookups
This chapter assumes you know how to create, read and change dictionaries, and that you understand mutable and immutable objects. It explains why key in d and d[key] stay fast as a dictionary grows, and what that requires of your keys.
The core idea
A dictionary is built on a hash table. A hash table is an array of slots. Python does not search the slots one by one. It turns the key into a number called a hash, then uses that number to decide which slot to look at first.
print(hash("apple") == hash("apple")) # True within one run
print(hash((1, 2)) == hash((1, 2))) # TrueThe same key always gives the same hash during one program run. Hashes of strings change between runs because Python randomizes them as a security measure. Never store a hash value and rely on it later.
Steps of a lookup
- Compute
hash(key). - Use part of that number to pick a starting slot.
- If the slot is empty, the key is absent.
- If the slot holds a key that is the same object, or that compares equal and has the same hash, return its value.
- Otherwise, the slot holds a different key. Python probes another slot chosen by a fixed rule and repeats from step 3.
Two different keys that land in the same slot cause a collision. Python resolves collisions by probing, as in step 5. CPython keeps the table sparse, so most lookups finish after one or two checks. It resizes the table when it fills up. Resizing is a cost paid occasionally, so adding a key is fast on average.
What the speed means
Lookup, insertion and deletion take constant time on average, written O(1). The time does not depend on how many entries the dictionary holds. Searching a list with in checks items one at a time, which is O(n).
from timeit import timeit
n = 100_000
as_list = list(range(n))
as_dict = dict.fromkeys(as_list)
print(timeit(lambda: n - 1 in as_list, number=200))
print(timeit(lambda: n - 1 in as_dict, number=200))The exact times depend on your machine. The dictionary result is typically orders of magnitude smaller. The worst case is O(n) when many keys collide, but normal keys rarely cause this.
The contract keys must follow
The lookup steps rely on one rule: keys that are equal must have equal hashes. If it is broken, an equal key can be looked for in the wrong slot and not be found.
This explains behavior you have already seen:
- A
listis unhashable because it is mutable. If its contents changed after insertion, its hash would change and the entry would be stranded in the wrong slot. - Numbers that compare equal share a hash, so they are the same key.
d = {1: "int"}
print(d[1.0]) # int
print(d[True]) # int
d[1.0] = "float"
print(d) # {1: 'float'}The entry keeps the original key 1, but the value is replaced.
Custom classes as keys
When you define __eq__ on a class, Python sets __hash__ to None, which makes instances unhashable. Define both, and base the hash on the same fields that __eq__ compares.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
seen = {Point(1, 2): "A"}
print(seen[Point(1, 2)]) # AWhy insertion order is kept
Modern CPython stores entries in a compact array in the order they were added. A separate sparse array of small integers points into it. The hash decides which index slot to check. The index then leads to the entry. This layout saves memory and explains why iteration follows insertion order.
Common errors
- Using a list, set or dict as a key raises
TypeError: unhashable type. - Defining
__eq__without__hash__makes instances unhashable. - Mutating a key object after insertion makes the entry unfindable.
- Using
inon a list inside a loop when a dictionary or set would make each check O(1).
Exercise
A class defines __eq__ comparing two fields, and its __hash__ returns hash(self.id), where id is only one of those fields. Do dictionary lookups still work, and what is the cost?
Show answer
Lookups still work, because equal objects have equal id values and so equal hashes, which satisfies the contract. The cost is more collisions: objects that share an id but differ in the other field land in the same slot, so lookups probe more and slow down.