Hash Tables: Hashing, Collisions and Python dict and set
A hash table answers "what value goes with this key?" in constant time on average, which is why it sits behind Python's dict and set and behind so many fast solutions to search problems. The word "average" matters, and this post explains where it comes from. Examples use Python 3.10 or later and only the standard library.
From key to bucket
A hash table stores its entries in an array of buckets. To place a key, it runs a hash function that turns the key into an integer, then reduces that integer to a bucket index, for example with hash(key) % number_of_buckets. Looking the key up later repeats the same computation and goes straight to the same bucket, with no scan of the other entries.
A usable hash function has two properties. It must be consistent: equal keys always produce equal hashes, or a lookup would search the wrong bucket. And it should spread different keys evenly over the buckets, so that no bucket collects many of them. Computing the hash takes time proportional to the size of the key (a long string has more characters to mix), which is usually treated as a constant.
Collisions: chaining and open addressing
There are far more possible keys than buckets, so two different keys will sometimes land in the same bucket. That is a collision, and every hash table needs a rule for it.
- Chaining: each bucket holds a small list of (key, value) pairs. A lookup goes to the bucket and compares the key against the few entries there.
- Open addressing: every entry lives directly in the array. If the computed slot is taken, the table probes other slots in a fixed sequence (the simplest is the next slot, then the one after) until it finds the key or an empty slot. Deletion needs care, because emptying a slot could break the probe sequence for keys stored beyond it; implementations mark deleted slots instead.
Load factor and resizing
The load factor is the number of entries divided by the number of buckets. As it rises, buckets get crowded (chaining) or probe sequences get long (open addressing), and operations slow down. So a hash table sets a threshold and, when the load factor passes it, allocates a larger bucket array (typically about twice the size) and reinserts every entry, because each key's bucket index depends on the number of buckets.
Here is a small chaining table that resizes when the load factor goes above 0.75. It prints only counts, not bucket positions, because Python salts the hashes of strings with a random value per process, so the positions change from run to run:
class ChainedHashTable:
def __init__(self, buckets=4):
self.buckets = [[] for _ in range(buckets)]
self.size = 0
def _bucket(self, key):
return self.buckets[hash(key) % len(self.buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value) # update an existing key
return
bucket.append((key, value))
self.size += 1
if self.size / len(self.buckets) > 0.75: # load factor check
self._resize(2 * len(self.buckets))
def get(self, key):
for k, v in self._bucket(key):
if k == key:
return v
raise KeyError(key)
def _resize(self, new_count):
old = self.buckets
self.buckets = [[] for _ in range(new_count)]
for bucket in old: # rehash every entry: O(n)
for k, v in bucket:
self._bucket(k).append((k, v))
table = ChainedHashTable()
for i, word in enumerate(["ant", "bee", "cat", "dog", "eel", "fox", "gnu"]):
table.put(word, i)
print(f"size {table.size}, buckets {len(table.buckets)}, "
f"load {table.size / len(table.buckets):.2f}")
print(table.get("dog"), table.get("gnu"))
size 1, buckets 4, load 0.25
size 2, buckets 4, load 0.50
size 3, buckets 4, load 0.75
size 4, buckets 8, load 0.50
size 5, buckets 8, load 0.62
size 6, buckets 8, load 0.75
size 7, buckets 16, load 0.44
3 6
A resize costs O(n), since every entry is rehashed. Because the bucket count doubles each time, resizes get rarer as the table grows, exactly like the copies in a growing dynamic array, and insertion is amortized O(1). The Amortized Analysis Calculator works through that arithmetic for a doubling array.
Average O(1), worst case O(n)
With a good hash function and a bounded load factor, each bucket holds only a constant number of entries on average, so lookup, insert and delete take O(1) time on average (or expected, when the hash function is chosen at random). That bound rests on an assumption about how the keys spread. If many keys hash to the same bucket, a lookup must compare against all of them, and in the extreme, when all n keys collide, each operation is O(n). That can happen through a poor hash function or through keys chosen deliberately to collide, which is one reason Python randomizes string hashes.
Two things a hash table does not do well: it keeps no sorted order (finding the smallest key or all keys in a range means looking at every entry), and it has no cheap "nearest key" query. When you need those, a sorted list with bisect or a balanced search tree fits better.
Python dict and set
dict maps keys to values and set stores keys alone; both are hash tables, so key in d, d[key], d[key] = v, del d[key], s.add(x) and x in s are all O(1) on average. Compare x in some_list, which is an O(n) scan.
Keys must be hashable. Immutable built-ins such as numbers, strings and tuples of hashable items qualify; a list does not, because its contents could change after it was stored, which would leave it in the wrong bucket.
point_names = {(0, 0): "origin", (3, 4): "corner"} # tuples are hashable
print(point_names[(3, 4)])
try:
bad = {[3, 4]: "corner"} # lists are not
except TypeError as err:
print("TypeError:", err)
seen = set()
for x in [5, 1, 5, 2, 1]:
seen.add(x)
print(sorted(seen), 2 in seen, 7 in seen)
corner
TypeError: unhashable type: 'list'
[1, 2, 5] True False
Since Python 3.7, the language guarantees that a dict keeps its keys in insertion order (see the Mapping Types section of the Python documentation). Sets make no ordering promise, which is why the example sorts before printing.
Worked example: two-sum in O(n)
Given a list of numbers and a target, find the indices of two different positions whose values add up to the target. The brute force tries every pair, O(n^2). With a dictionary from each value to its index, one pass is enough: for each x, ask whether target - x has already been seen. That is O(n) time on average and O(n) extra space, a direct trade of memory for time. The test at the end compares both versions on 1,000 random small inputs with a fixed seed; because the two can find different valid pairs, it checks that both agree on whether a pair exists and that the fast answer really sums to the target.
import random
def two_sum_slow(nums, target): # O(n^2): try every pair
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
def two_sum_fast(nums, target): # O(n) average: one pass with a dict
index_of = {} # value -> index where we saw it
for j, x in enumerate(nums):
i = index_of.get(target - x)
if i is not None:
return (i, j)
index_of[x] = j
return None
print(two_sum_fast([2, 7, 11, 15], 9))
print(two_sum_fast([3, 3], 6))
print(two_sum_fast([1, 2, 3], 7))
random.seed(42)
for _ in range(1000):
nums = [random.randint(-10, 10) for _ in range(random.randint(0, 8))]
target = random.randint(-15, 15)
slow, fast = two_sum_slow(nums, target), two_sum_fast(nums, target)
assert (slow is None) == (fast is None)
if fast is not None:
i, j = fast
assert i < j and nums[i] + nums[j] == target
print("1000 random cases agree")
(0, 1)
(0, 1)
None
1000 random cases agree
Note the order inside the loop: the lookup comes before index_of[x] = j, so an item is never paired with itself, and [3, 3] with target 6 still works. If the list were sorted, a two-pointer scan would solve the same problem with O(1) extra space; see two pointers and sliding window.
Worked example: counting with Counter
Counting occurrences is the other everyday use. collections.Counter is a dict subclass that maps each item to its count and returns 0 for missing keys instead of raising KeyError:
from collections import Counter
text = "the cat sat on the mat the end"
counts = Counter(text.split())
print(counts.most_common(2))
print(counts["cat"], counts["dog"])
[('the', 3), ('cat', 1)]
1 0
Counting n words takes O(n) time on average, one hash-table update per word.
Check yourself
- Why can't a hash table promise O(1) in the worst case? (If many keys land in one bucket, an operation must compare against all of them.)
- Why must a resize rehash every key instead of copying buckets as they are? (A key's bucket index depends on the number of buckets.)
- You need the 10 smallest keys of a large dict often. Is a dict the right structure? (No; it keeps no sorted order, so each query scans everything. Consider a heap or a sorted structure.)