Hash Maps & Sets
How hashing works
A hash function turns a key (like "apple") into a number, which picks a bucket in an internal array. So finding a key doesn't require searching; you jump straight to its bucket.
Python's hash structures
| Structure | Stores | Example |
|---|---|---|
dict | key → value | ages = {"Ana": 25} |
set | unique keys | seen = {1, 2, 3} |
collections.Counter | key → count | Counter("banana") |
collections.defaultdict | key → value with a default | defaultdict(list) |
Costs
| Operation | Average | Worst (many collisions) |
|---|---|---|
| Insert, look up, delete | O(1) | O(n) |
Collisions
Two keys can land in the same bucket. Hash tables handle this (chaining or probing) and resize when they get full, so operations stay O(1) on average.
Rules
- Keys must be hashable (immutable):
str,int,tuple✅.listanddict❌. - Sets and dicts don't keep duplicates; a set is perfect for "have I seen this?".
💡 When you write a nested loop to find something, ask: "Could a hash map remember it instead?" That's the most common way to go from O(n²) to O(n).
Example
from collections import Counter, defaultdict
# Count words
text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
# Group words by first letter
groups = defaultdict(list)
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
groups[word[0]].append(word)
print(dict(groups)) # {'a': ['apple', 'avocado'], 'b': [...], 'c': ['cherry']}
# First repeated item using a set
def first_repeat(items):
seen = set()
for x in items:
if x in seen:
return x
seen.add(x)
return None
print(first_repeat([3, 8, 1, 8, 3])) # 8