Hash Maps
A hash map (also called a dictionary or associative array) stores key → value pairs. It is a hash table where every bucket entry holds a key and its value. The key decides the bucket; the value just travels along. Looking up the value for a key is O(1) on average.
Examples: a phone book (name → number), a word counter (word → count), a cache (URL → page), a configuration (setting → value).
Buckets of key-value pairs
The animation shows where the keys go; in a hash map each stored key also carries its value. With 7 buckets, the product codes below hash like this:
Max and Ian collide in bucket 0, and Kim and Sam collide in bucket 2. Putting Kim again doesn't add a second entry: in a hash map it updates the existing key's value.
Implementation
class HashMap:
def __init__(self, size=7):
self.buckets = [[] for _ in range(size)]
def _bucket(self, key):
return self.buckets[sum(ord(c) for c in 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) # existing key: update
return
bucket.append((key, value)) # new key: add a pair
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
def remove(self, key):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
del bucket[i]
return True
return False
stock = HashMap()
stock.put("Max", 12)
stock.put("Ian", 4)
stock.put("Kim", 30)
stock.put("Sam", 7)
print("Sam:", stock.get("Sam"))
stock.put("Kim", 25) # update, not a new entry
stock.remove("Max")
print("Max:", stock.get("Max", "not found"))
for i, bucket in enumerate(stock.buckets):
if bucket:
print(i, bucket)Sam: 7
Max: not found
0 [('Ian', 4)]
2 [('Kim', 25), ('Sam', 7)]
Python's dict
Python's dict is a hash map that also remembers insertion order (since Python 3.7). The essentials:
ages = {"Ana": 31, "Ben": 27}
ages["Cleo"] = 35 # insert
ages["Ben"] = 28 # update
print(ages["Ana"]) # lookup; raises KeyError if missing
print(ages.get("Dev", "unknown"))
print("Cleo" in ages) # membership tests the keys
del ages["Ana"]
for name, age in ages.items():
print(name, age)31
unknown
True
Ben 28
Cleo 35
Pattern: counting
Counting occurrences is the classic hash map job. dict.get(key, 0) + 1 works, and collections.Counter does it for you:
from collections import Counter
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
c = Counter(text.split())
print(c.most_common(2)){'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
[('the', 3), ('and', 2)]
Pattern: grouping
Map each key to a list of items. collections.defaultdict(list) creates the empty list the first time a key is used:
from collections import defaultdict
words = ["listen", "google", "silent", "enlist", "elgoog", "stone", "notes"]
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w) # anagrams share their sorted letters
for key, group in groups.items():
print(key, group)eilnst ['listen', 'silent', 'enlist']
eggloo ['google', 'elgoog']
enost ['stone', 'notes']
Pattern: "have I seen the complement?"
Find two numbers in a list that add up to a target. The naive way checks every pair, O(n²). With a hash map from value to index, one pass is enough: for each number, ask whether target - number has already been seen.
def two_sum(nums, target):
index_of = {}
for i, n in enumerate(nums):
need = target - n
if need in index_of:
return index_of[need], i
index_of[n] = i
return None
prices = [14, 3, 22, 9, 17, 5]
print(two_sum(prices, 26)) # 9 + 17
print(two_sum(prices, 100))(3, 4)
None
Tip: Whenever a solution has a nested loop that searches for "a matching item", ask whether a hash map could remember the items instead. It often turns
O(n²)intoO(n).
Rules for keys
| Rule | Why |
|---|---|
Keys must be hashable (immutable): str, int, tuple |
a key's hash must never change |
| Keys are unique | putting an existing key overwrites its value |
| Values can be anything | they are not hashed |
Lookups compare keys with == after matching the hash |
two keys that are equal must have equal hashes |
Test yourself
What happens when you put a key that already exists in a hash map?
- A second entry is added
- Its value is replaced
- An error is raised
- The key is removed
What does counts.get(word, 0) return when word is not a key?
- None
- KeyError
- 0
- An empty list
Using a hash map, what is the time complexity of the one-pass two-sum algorithm?
- O(1)
- O(n)
- O(n log n)
- O(n²)