How a hash map finds a key
A hash map finds one key among a million without searching. Every lookup is the same three moves: hash the key, pick a bucket, compare. Here they are, drawn one at a time.
01 The question
You store ages by name and read one back. The map holds four names here, but it could hold four million, and ages["mia"] would still return about as fast. Nothing is sorted and nothing is scanned. So how does it know where "mia" is?
02 The naive picture: check every key
The obvious way is a list of pairs: walk along it and compare each name with "mia" until one matches. That works, but the work grows with the list. A missing key is the worst case, because you have to check every pair to be sure it is not there.
A hash map avoids the walk with the same trick as an array: it works out where to look, then looks only there.
03 Move 1: turn the key into a number
A hash function takes a key and returns an integer, its hash. The one rule that matters: the same key must always give the same hash. Different keys should usually give different hashes, but that is a hope, not a promise.
To keep the numbers small, this page uses a toy hash: add up the character codes of the name.
Real hash functions mix the bits far more thoroughly. The toy hash gives "eve" and "leo" the same number, for example, because they add up to the same total. A good hash makes that rare.
04 Move 2: squeeze the number into a bucket
Behind the map is a plain array of buckets, here 8. A hash can be any size, so the map turns it into a bucket number with the remainder: hash % 8 is always between 0 and 7. Reading that bucket is an array index, so it is instant.
| Key | Toy hash | hash % 8 |
|---|---|---|
| "ana" | 304 | 0 |
| "bo" | 209 | 1 |
| "dan" | 307 | 3 |
| "mia" | 311 | 7 |
Storing a key is the same two moves, then a write. Watch the four names go in.
- just stored
An empty map with 8 buckets. Each bucket holds its entries: a key, its value, and the key’s hash. For now every bucket is empty.
Many real maps keep the bucket count a power of two, so hash % 8 can be done as hash & 7, which keeps the lowest bits and is cheaper than division. Java’s HashMap and CPython’s dict both do this.
05 Move 3: compare the key
The bucket might hold the key you want, or a different key that happened to land there. So the map always checks. Many implementations store each key’s hash next to it and compare the hashes first, because comparing two integers is cheaper than comparing two long strings.
- bucket picked
- key matches
- just worked out
ages["mia"] is called. The map has the key and its 8 buckets. Nothing is read yet.
Now a name that was never stored. "amy" lands in bucket 7 too, and only the comparison stops the map from returning Mia’s age.
- bucket picked
- key does not match
- just worked out
ages["amy"] is called. The map has the key and its 8 buckets. Nothing is read yet.
Two keys sharing a bucket is called a collision. Here the map could stop, because each bucket holds one entry. Real maps let a bucket hold more, or try other buckets; that is the next tutorial.
06 Ask Python for a hash
Python exposes the hash function its dict uses. Small integers hash to themselves. Strings get a large number that changes every time you start Python.
Since Python 3.3, string hashes are seeded with a random value per process. Within one run, "mia" always hashes the same, which is all a map needs. Across runs it changes, so an attacker cannot work out in advance which keys will all land in one bucket. Set PYTHONHASHSEED=0 to turn the randomness off.
07 When it breaks
equals() without hashCode()Equal keys with different hashesIn Java, if two objects are equals they must return the same hashCode. Override only equals, and an equal copy of a key hashes to a different bucket, so map.get returns null.d[[1, 2]] = "x"A key that can changeIf a key changed after it was stored, its hash would change and the map would look in the wrong bucket. Python refuses lists as keys with TypeError: unhashable type. Java lets you mutate a key object, and the entry is then effectively lost.d[0.1 + 0.2]Keys that only look equal0.1 + 0.2 is not exactly 0.3 in floating point, so it hashes differently and misses. Round, or use integers or strings, for keys that come from arithmetic.HashMap iterates in bucket order. CPython’s dict keeps insertion order (guaranteed since 3.7) only because it stores the entries in a separate array.