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 time.
Why It Matters
- The single most common algorithmic speedup: Replacing repeated membership scans over a list with lookups in a
setordicteliminates 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 " 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
Basic bucket index formula:
As the load factor (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
listversus nanosecond hash lookup onset. - Because
1 == 1.0 == Trueand their hash values are equal, Python treats them as the exact same dictionary key—keeping the first key object1while overwriting its value to'c'. - Mutable lists are unhashable by design and raise
TypeErrorwhen used as dictionary keys (see k1.py.mutability).
Common Pitfalls
- "Hash tables are guaranteed ": is the expected average case; worst-case hash collisions or table resize steps take 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 raiseTypeError. - Relying on iteration order of a
set: Unlikedict(which guarantees insertion order),setiteration order is arbitrary and shifts across runs. - Persisting Python's built-in
hash()across processes: BecausePYTHONHASHSEEDrandomizes string/bytes hashes on every interpreter startup, never usehash(s)for persistent cache keys or database IDs—use a deterministic cryptographic hash fromhashlib(such ashashlib.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.sha256over 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
HashingVectorizerprojects 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
- Python Mapping Types –
dict: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict collectionsModule (Counter,defaultdict): https://docs.python.org/3/library/collections.html- Raymond Hettinger's PyCon 2017 talk Modern Python Dictionaries: https://www.youtube.com/watch?v=npw4s1QTmPg
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