Hash Tables and Python's dict / set

A hash table maps a key's hash value to a candidate bucket slot and confirms matches via equality comparison. With good hashing and load-factor control, lookups, insertions, and deletions run in average O(1) time.

One-Line Definition

A hash table computes a hash value from a key to locate a candidate slot in an underlying array, then verifies the key via an equality check (==). With well-distributed hashes and load-factor resizing, lookup, insertion, and deletion run in average O(1)O(1) time.

Why It Matters

  • The single most common algorithmic speedup: Replacing repeated O(n)O(n) membership scans over a list with O(1)O(1) lookups in a set or dict eliminates quadratic bottlenecks (with actual gains depending on collection size and key hashing cost).
  • Powers caching, deduplication, frequency counting, indexing, and dynamic-programming memoization (see k2.algo.dynamic-programming).

Operating Boundaries

Stating that hash-table operations are "average O(1)O(1)" treats hashing and key equality comparisons as constant-time steps; hashing very long strings, custom objects, or pathological collision chains increases actual cost. In AI systems, response-cache keys must hash the model ID, sampling parameters, and system prompt version alongside the user prompt—never the raw prompt string alone.

How It Works / Diagram

Figure 1

Basic bucket index formula:

index=hash(k) mod m \text{index} = \text{hash}(k) \bmod m

As the load factor α=n/m\alpha = n/m (number of stored entries divided by total bucket slots) rises, hash collisions become more frequent—so a hash table automatically allocates a larger bucket array and re-indexes before getting too full.

CPython's dict uses open addressing with a compact entry array that preserves insertion order (introduced in CPython 3.6 and guaranteed by the language specification since Python 3.7): see the implementation notes in https://github.com/python/cpython/blob/main/Objects/dictobject.c and the Python 3.7 release notes (https://docs.python.org/3/whatsnew/3.7.html). String hashes are salted randomly per process by default to prevent algorithmic hash-collision DoS attacks: https://docs.python.org/3/reference/datamodel.html#object.__hash__.

Runnable Example

Comparing list vs. set lookup latency, building a minimal separate-chaining hash map to inspect collisions, testing hashability invariants, and using Counter, defaultdict, and order-preserving deduplication (recorded on Python 3.15.0):

# File: examples/12_hash_table.py
# Hash tables: key --hash function--> bucket slot, average O(1) lookup (Python's dict and set)
from timeit import timeit
n = 100_000
data_list, data_set = list(range(n)), set(range(n))
print(f"Lookup across {n} elements: list {timeit(lambda: n-1 in data_list, number=200)/200*1e6:.0f} µs"
      f" | set {timeit(lambda: n-1 in data_set, number=200)/200*1e9:.0f} ns")

# Minimal separate-chaining hash map to observe collisions directly
class HashMap:
    def __init__(self, cap=8): self.buckets = [[] for _ in range(cap)]
    def _idx(self, k): return hash(k) % len(self.buckets)
    def put(self, k, v):
        b = self.buckets[self._idx(k)]
        for i, (kk, _) in enumerate(b):
            if kk == k: b[i] = (k, v); return
        b.append((k, v))
    def get(self, k):
        for kk, v in self.buckets[self._idx(k)]:
            if kk == k: return v
        raise KeyError(k)
m = HashMap(4)
for k in ["apple", "pear", "fig", "kiwi", "plum", "lime"]: m.put(k, len(k))
print("get('plum') =", m.get("plum"), "| Bucket lengths:", [len(b) for b in m.buckets], "(string hashes are randomized per process startup)")

# Keys must be hashable; equal objects MUST have equal hashes
print("hash(1) == hash(1.0) == hash(True):", hash(1) == hash(1.0) == hash(True), "-> Treated as the same key in a dict:", {1: "a", 1.0: "b", True: "c"})
try: {[1, 2]: "x"}
except TypeError as e: print("Mutable list cannot be a key:", e)

# Everyday patterns: counting, grouping, order-preserving deduplication
from collections import Counter, defaultdict
words = "the cat and the hat and the bat".split()
print("Top 2 word frequencies:", Counter(words).most_common(2))
groups = defaultdict(list)
for w in words: groups[len(w)].append(w)
print("Grouped by length:", dict(groups))
print("Order-preserving dedup:", list(dict.fromkeys(words)))

Recorded output:

Lookup across 100000 elements: list 656 µs | set 64 ns
get('plum') = 4 | Bucket lengths: [2, 4, 0, 0] (string hashes are randomized per process startup)
hash(1) == hash(1.0) == hash(True): True -> Treated as the same key in a dict: {1: 'c'}
Mutable list cannot be a key: cannot use 'list' as a dict key (unhashable type: 'list')
Top 2 word frequencies: [('the', 3), ('and', 2)]
Grouped by length: {3: ['the', 'cat', 'and', 'the', 'hat', 'and', 'the', 'bat']}
Order-preserving dedup: ['the', 'cat', 'and', 'hat', 'bat']
  • Lookup across 100,000 items: The timing log shows microsecond linear scanning on list versus nanosecond hash lookup on set.
  • Because 1 == 1.0 == True and their hash values are equal, Python treats them as the exact same dictionary key—keeping the first key object 1 while overwriting its value to 'c'.
  • Mutable lists are unhashable by design and raise TypeError when used as dictionary keys (see k1.py.mutability).

Common Pitfalls

  • "Hash tables are guaranteed O(1)O(1)": O(1)O(1) is the expected average case; worst-case hash collisions or table resize steps take O(n)O(n) time.
  • Mutating an object used as a dictionary key: If a custom class overrides __eq__ without defining a consistent immutable __hash__, lookups will silently fail or raise TypeError.
  • Relying on iteration order of a set: Unlike dict (which guarantees insertion order), set iteration order is arbitrary and shifts across runs.
  • Persisting Python's built-in hash() across processes: Because PYTHONHASHSEED randomizes string/bytes hashes on every interpreter startup, never use hash(s) for persistent cache keys or database IDs—use a deterministic cryptographic hash from hashlib (such as hashlib.sha256).

Relevance to AI Engineering

  • Tokenizer vocabularies: Mapping token strings to integer token IDs during tokenization is backed by a hash table.
  • LLM response and embedding caches: Deterministic hashes (e.g., hashlib.sha256 over a canonical JSON payload of model + temperature + messages) index exact-match caches.
  • Corpus deduplication: Pre-training pipelines use exact cryptographic hashes for exact document deduplication and Locality-Sensitive Hashing (MinHash / LSH) for near-duplicate removal: https://en.wikipedia.org/wiki/Locality-sensitive_hashing
  • Feature hashing (the hashing trick): scikit-learn's HashingVectorizer projects arbitrary text tokens directly into a fixed-width feature vector without storing an in-memory vocabulary dictionary: https://scikit-learn.org/stable/modules/feature_extraction.html#feature-hashing

Further Reading

Concept Check

If two distinct keys happen to produce the exact same hash value (a hash collision), will inserting the second key overwrite the first key's entry in a dictionary?

Reference answer: No. After matching the hash slot, the hash table also checks key equality (k1 == k2); if the two keys are not equal, the collision-resolution mechanism (probing or chaining) stores both entries separately.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Execution log: 12_hash_table.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram