Skip to content

How a hash map finds a key

BasicsUnder the hood

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?

Python
ages = {}
ages["ana"] = 31
ages["bo"] = 25
ages["dan"] = 40
ages["mia"] = 29
ages["mia"] # 29

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.

List of pairsEvery key, worst caseTwice as many keys means twice as many comparisons.
Hash mapHash, index, compareThe same three moves whether it holds four keys or four million.

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.

Python
def toy_hash(key):
return sum(ord(ch) for ch in key)
toy_hash("mia") # 109 + 105 + 97 = 311

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.

Where each key goes in a map with 8 buckets
KeyToy hashhash % 8
"ana"3040
"bo"2091
"dan"3073
"mia"3117

Storing a key is the same two moves, then a write. Watch the four names go in.

Storing four keys
Step 1 of 5
Hash —Bucket —
Buckets · 8
0empty
1empty
2empty
3empty
4empty
5empty
6empty
7empty
  • 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.

— key

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.

Looking up "mia"
Step 1 of 4
Buckets read 0
Buckets · 8
0ana: 31
1bo: 25
2empty
3dan: 40
4empty
5empty
6empty
7mia: 29
The three moves
Empty
  • bucket picked
  • key matches
  • just worked out

ages["mia"] is called. The map has the key and its 8 buckets. Nothing is read yet.

"mia" key

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.

Looking up "amy", which is not there
Step 1 of 4
Buckets read 0
Buckets · 8
0ana: 31
1bo: 25
2empty
3dan: 40
4empty
5empty
6empty
7mia: 29
The three moves
Empty
  • 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.

"amy" key

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.

Shell
$ python3 -c 'print(hash(42), hash("mia"), hash("mia") % 8)'
42 1527480849350889797 5
$ python3 -c 'print(hash(42), hash("mia"), hash("mia") % 8)'
42 -696677870184026274 6

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.
Expecting the keys in orderKeys live where their hash puts them, not in the order you added them. Java’s 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.

08 Check yourself

Question

The map has already found the right bucket. Why does it still compare the key?

Question

A map has 8 buckets. A key hashes to 45. Which bucket does it go in?

Question

A Java class overrides equals but not hashCode. You put one object, then get with an equal copy. What do you usually get?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?