Kodewick
Start learning →
Hash functions and __hash__18 / 52

Hash functions and __hash__

Lesson 18 of 52 · Part 4 · Hash tables: dict and set · about 18 minutes

A hash function turns a key into an integer that says which slot it belongs in, which is why dict and set lookups are O(1) on average; a class of your own needs __eq__ and __hash__ to be used as a key.

A service has a million usernames and checks at login whether a name is there. In a list, name in users can take a million comparisons; in a set it takes about one. A set doesn't compare its way through; it works out from the name which slot it belongs in and looks only there. The function that turns a key into that integer is a hash function. dict, set, database indexes and caches are all built on it, and how good it is decides whether a lookup is O(1) or slides back to O(n).

From a key to an index

The simplest hash function: the table has m slots, and the integer k goes in slot k % m. Work it out once when storing, again when looking up, and look only in that slot, with no comparisons against other keys.

table (indexes 0–9)0123456789

Table size 10, h(k) = k % 10: each key works out its own slot; finding 47 is also a sum, then one slot; 57 also lands on 7 and runs into 47
main.py
1m = 102table = [None] * m3 4def put(k):5    table[k % m] = k6 7def find(k):8    return table[k % m] == k9 10for k in [23, 47, 81, 15]:11    put(k)12print(table)13print(find(47), find(57))14put(57)                  # 57 % 10 = 7: overwrites 4715print(table)16print(find(47))
Output
[None, 81, None, 23, None, 15, None, 47, None, None]
True False
[None, 81, None, 23, None, 15, None, 57, None, None]
False

There are only so many slots but endlessly many keys, so collisions are certain: different keys land on the same slot. This simplest version just overwrote 47, which is wrong. Handling collisions is the job of the next two lessons: dict looks further along for a free slot (open addressing); the other way hangs a chain off each slot (separate chaining). This lesson takes the other half: making collisions rare.

Choose one

Table size 10, h(k) = k % 10, and 23 is already in slot 3. Which key would collide with 23?

Guess the outputA wrong guess is fine

Using this stage's simplest table (a collision just overwrites), put in 10, 3 and 17 in turn. What does it print?

1m = 72table = [None] * m3for k in [10, 3, 17]:4    table[k % m] = k5print(table)

Hashing a string

A string has to become an integer first, then % m. The obvious idea is to add up each character's code (ord(c)). The trouble is that addition ignores order: eat, tea and ate have the same letters, so the same sum, and all land in one slot.

sum(ord) % 70123456

A bad hash: add the letter codes, then % 7. eat, tea and ate all sum to 314 and crowd into bucket 6

Switch to a polynomial hash: left to right, for each character multiply what you have so far by 31, then add the character. Now each character's share depends on its position: eat is 101·31² + 97·31 + 116 and tea is 116·31² + 101·31 + 97, which differ. Taking % m at every step keeps the number small and gives the same result as % m at the end.

polynomial % 70123456

A polynomial hash: h = h * 31 + ord(c), % 7 at each step. The same 6 words land in 6 different buckets
starth = 0
'e': 0 × 31 + 101h = 101
'a': 101 × 31 + 97h = 3228
't': 3228 × 31 + 116h = 100184
'eat' one character at a time (no modulo yet): for each character, multiply h by 31, then add its code
main.py
1def bad_hash(s, m):2    return sum(ord(c) for c in s) % m3 4def poly_hash(s, m):5    h = 06    for c in s:7        h = (h * 31 + ord(c)) % m8    return h9 10words = ["eat", "tea", "ate", "tan", "nat", "bat"]11print([bad_hash(w, 7) for w in words])12print([poly_hash(w, 7) for w in words])13print(101 * 31 * 31 + 97 * 31 + 116, poly_hash("eat", 1000000))
Output
[6, 6, 6, 1, 1, 3]
[0, 2, 6, 3, 4, 1]
100184 100184

Java's String.hashCode() is exactly this base-31 polynomial, except that it takes no modulus and lets the 32-bit integer overflow.

Choose one

If a hash just adds up the character codes, which pair is sure to collide?

Guess the outputA wrong guess is fine

Using h = h * 31 + ord(c) (no modulo yet) on "ab" and "ba". What does it print?

1def poly(s):2    h = 03    for c in s:4        h = h * 31 + ord(c)5    return h6 7print(poly("ab"), poly("ba"))
Exercise 1

A polynomial hash by hand

Finish str_hash(s, m): h starts at 0, and for each character c, h = (h * 31 + ord(c)) % m; return h at the end.

It should print
[0, 2, 6, 3, 4, 1]
354 0
exercise1.py
1def str_hash(s, m):2    # h starts at 0; for each character multiply by 31, add ord(c), % m at every step3    return 04 5words = ["eat", "tea", "ate", "tan", "nat", "bat"]6print([str_hash(w, 7) for w in words])7print(str_hash("abc", 1000), str_hash("", 7))
Output
Press Run or Ctrl+Enter

What makes a hash good

Six words are too few. Try all 125 three-letter words made of a to e, and count how many buckets get used and how full the fullest one is:

main.py
1from itertools import product2 3def bad_hash(s, m):4    return sum(ord(c) for c in s) % m5 6def poly_hash(s, m):7    h = 08    for c in s:9        h = (h * 31 + ord(c)) % m10    return h11 12def spread(hash_fn, keys, m):13    sizes = [0] * m14    for k in keys:15        sizes[hash_fn(k, m)] += 116    used = sum(1 for x in sizes if x > 0)17    return used, max(sizes)18 19words = ["".join(p) for p in product("abcde", repeat=3)]20print(len(words), "words")21print("letter sum % 101: used", *spread(bad_hash, words, 101))22print("polynomial % 101: used", *spread(poly_hash, words, 101))23print("polynomial % 31 : used", *spread(poly_hash, words, 31))
Output
125 words
letter sum % 101: used 13 19
polynomial % 101: used 89 2
polynomial % 31 : used 5 25

Adding the letters gives only 13 different sums (three letters sum to at least 291 and at most 303), so 13 of the 101 buckets are used and the fullest holds 19 words. The polynomial uses 89 buckets with at most 2 in each.

The third line is a different trap: the base 31 equals the table size 31. h * 31 % 31 is always 0, so every earlier letter is wiped out and only the last letter counts: 5 buckets of 25 words each. Integers are the same: if every key is a multiple of 10 and the table size is 10, k % 10 is always 0; with a table size of 11 (no common factor with 10) they go one per slot.

RequirementWhyCounterexample
The same key always gives the same valuestoring and finding must reach the same slotcomputing it from random or the clock
Equal keys must hash equal1 and 1.0 are equal, so they must be one keywriting __eq__ but not __hash__
Spread evenlyone or two per slot on average keeps lookups O(1)adding letters: anagrams all collide
Fast to computeevery lookup computes it firstturning a big object into a string every time

The reverse is not required: two keys with equal hashes are not necessarily equal (that is a collision), so once at the slot, == still has to confirm.

In interviews: "Why are table sizes often prime?": whenever m shares a factor with a pattern in the keys (a step, a base), some slots are never used; a prime shares a factor with nothing. Python's dict uses powers of two because its hash values are already well mixed, so the low bits are enough.

Choose one

The polynomial hash uses base 31, and the table size is also 31. What happens?

Choose one

Which of these is not something a hash function has to guarantee?

Python's hash()

Python has a hash ready for every immutable built-in type: hash(x) gives it to you. A few rules:

main.py
1print(hash(5), hash(100), hash(0))2print(hash(-1), hash(-2))3print(hash(1) == hash(1.0) == hash(True))4print(hash("abc") == hash("abc"))5print(hash((1, 2)) == hash((1, 2)))6print({10, 3, 17})
Output
5 100 0
-2 -2
True
True
True
{17, 10, 3}
  • A small integer hashes to itself. The one exception is -1: CPython's C code uses -1 to mean "an error happened", so hash(-1) is -2.
  • Equal values hash equal: 1 == 1.0 == True, all three hash to 1, and in a dict they are one key.
  • The last line: a set's table starts with 8 slots; 17, 10 and 3 land in slots 17 % 8 = 1, 2 and 3, and printing walks the slots in order, giving {17, 10, 3}.
  • A string's hash changes on every run. At startup Python picks a random seed for string hashes, so nobody can craft a pile of colliding keys to slow a server down (a hash-flooding attack). Within one run hash("abc") == hash("abc"), but never print hash() of a string, and never print a set of strings as it is: its order can change from run to run, so sorted() it first.
Guess the outputA wrong guess is fine

Three keys, 1, 1.0 and True. What does it print?

1d = {1: "a", 1.0: "b", True: "c"}2print(d, len(d))
Guess the outputA wrong guess is fine

Hashes of three built-in values. What does it print?

1print(hash(-1), hash(10), hash(1.0))

Your own class: __eq__ and __hash__

A class you write compares by identity by default: == means is, and the hash comes from the object's identity too. Two Points with the same values are two different keys:

main.py
1class Point:2    def __init__(self, x, y):3        self.x = x4        self.y = y5 6a, b = Point(1, 2), Point(1, 2)7print(a == b, len({a, b}))8 9class Point2:10    def __init__(self, x, y):11        self.x = x12        self.y = y13 14    def __eq__(self, other):15        return isinstance(other, Point2) and (self.x, self.y) == (other.x, other.y)16 17print(Point2(1, 2) == Point2(1, 2))18try:19    s = {Point2(1, 2)}20except TypeError as e:21    print("TypeError:", e)22 23class Point3:24    def __init__(self, x, y):25        self.x = x26        self.y = y27 28    def __eq__(self, other):29        return isinstance(other, Point3) and (self.x, self.y) == (other.x, other.y)30 31    def __hash__(self):32        return hash((self.x, self.y))33 34a, b = Point3(1, 2), Point3(1, 2)35print(a == b, len({a, b}), Point3(1, 2) in {a})
Output
False 2
True
TypeError: unhashable type: 'Point2'
True 1 True

When you write only __eq__, Python sets __hash__ to None for you and the class becomes unhashable. The reason is the rule: a == b requires hash(a) == hash(b). Once you change what "equal" means, the old identity-based hash no longer keeps that rule, and Python would rather not let you use it. So write both: __eq__ compares some fields, and __hash__ hashes a tuple of those same fields.

TypeCan be a key?Why
int, float, stryesimmutable
tuple (all items hashable)yesimmutable, hashed from its items
tuple (holding a list)noan item cannot be hashed
list, dict, setnomutable: after a change it sits in the wrong slot
your class, nothing writtenyesby identity: equal only if is
only __eq__no__hash__ is set to None
both __eq__ and __hash__yesby value
What can be a dict key or a set element: only immutable things; for your own class it depends on what you wrote

Why not a list? The hash is worked out from the contents at the moment it goes in. Change the contents afterwards and it sits in a wrong slot: the new contents point to another slot, and it can never be found again. Here is the demonstration on a small hand-made table, with sum as the list's hash:

main.py
1m = 102table = [None] * m3 4key = [1, 2]5table[sum(key) % m] = key        # pretend sum is a list's hash: into slot 36print(sum(key) % m)7key.append(5)                    # change it after it went in8i = sum(key) % m9print(i, table[i] is key)        # look by the new contents, in slot 8: not there10print(table[3] is key)           # it is still lying in slot 311 12pos = {(0, 0): "start", (2, 3): "goal"}13print(pos[(2, 3)])14try:15    bad = {[0, 0]: "start"}16except TypeError as e:17    print("TypeError:", e)
Output
3
8 False
True
goal
TypeError: unhashable type: 'list'

A tuple cannot change, so its hash always matches after it goes in. That is why coordinates and keys made of several fields are tuples.

Choose one

A class defines __eq__ but not __hash__. What happens when you put one of its objects in a set?

Exercise 2

Cards that deduplicate

A hand has duplicates. Give Card an __eq__ and a __hash__ so that two cards with the same rank and suit count as one: set(hand) drops the duplicates, and in finds a card by value.

It should print
3
True
exercise2.py
1class Card:2    def __init__(self, rank, suit):3        self.rank = rank4        self.suit = suit5    # add __eq__ and __hash__: both look at rank and suit6 7hand = [Card("A", "S"), Card("K", "H"), Card("A", "S"), Card("K", "H"), Card("Q", "D")]8print(len(set(hand)))9print(Card("Q", "D") in set(hand))
Output
Press Run or Ctrl+Enter

How you write it at work

For a class that compares by value and can be a key, use @dataclass(frozen=True): it writes __eq__ and __hash__ from the fields, and frozen=True stops the fields from changing, which is exactly "it must not change after it goes in".

main.py
1from dataclasses import dataclass2 3@dataclass(frozen=True)4class Point:5    x: int6    y: int7 8seen = {Point(1, 2), Point(1, 2), Point(3, 4)}9print(len(seen), Point(3, 4) in seen)10 11names = {"bob", "amy", "cat"}12print(sorted(names))             # a set of strings: sort before printing
Output
2 True
['amy', 'bob', 'cat']
  • A key made of several values is simply a tuple: dist[(r, c)], cache[(n, k)].
  • Writing __hash__ yourself: hash((self.a, self.b)), with the same fields __eq__ compares.
  • Don't use objects that change as keys. Plain @dataclass (without frozen) writes __eq__, so __hash__ is None and it cannot be a key: that is protecting you.
  • The cost of hashing: an int is O(1); a string is O(length) the first time, then the result is stored on the string object and reused; a tuple combines its items' hashes again every time.
Choose one

Which of these can be a dict key?

Summary

Take-away

Hash functions: from a key to a slot

  • A hash function turns a key into an integer, and % m gives the slot; different keys on one slot are a collision, and collisions are certain
  • A good hash: the same key gives the same result, equal keys hash equal, it spreads evenly, it is fast
  • Strings use the polynomial h = h * 31 + ord(c), so position counts; the base and the table size must share no factor
  • hash(): a small int is itself, 1, 1.0 and True are one key, a string changes every run (don't print it)
  • Your own class: write __eq__ and __hash__ together over the same fields; a mutable list cannot be a key, use a tuple
1h = (h * 31 + ord(c)) % m2def __hash__(self):3    return hash((self.x, self.y))4@dataclass(frozen=True)5pos[(r, c)] = v