Hashing for lookup
Hashing for lookup means putting keys in a dict or set so average membership and retrieval are O(1) instead of scanning a list. It is the standard way to turn nested loops into one pass.
Detailed Explanation
x in list walks the list. x in set hashes x and jumps to a bucket. For a membership test inside a loop over n items, the list version is O(n²) and the set version is O(n) average. That swap is the most common complexity fix in Python.
A dict stores a value next to the key. "Have I seen this sku, and where?" is index[sku] = i. Two-sum on an unsorted list is a dict from value to index: as you walk, you ask whether target - value is already a key. Anagram grouping is a dict from a sorted-letter key to a list of words.
Keys must be hashable and their hash must be stable while they sit in the table. Immutables (int, str, tuple of hashables, frozenset) work. Lists and dicts do not. If you override __eq__, you must override __hash__ in a matching way, or set __hash__ = None.
Average O(1) is not a worst-case guarantee. A bad hash distribution degrades toward O(n). CPython randomises string hashes per process to make that hard to exploit from the outside. Still, treat O(1) as average, and do not use a dict as a timing-safe structure.
Build the table once when the keys are known. Rebuilding it on every query wastes the advantage. When keys are integers in a tight range, a list indexed by the integer can be faster and simpler than a dict.
Hashing does not preserve order of values. Dicts preserve insertion order of keys (3.7+). If you needed sorted order, sort, or use a tree structure.
Code Examples
def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
seen: dict[int, int] = {}
for i, value in enumerate(nums):
need = target - value
if need in seen:
return seen[need], i
seen[value] = i
return None
print(two_sum([2, 7, 11, 15], 9)) # (0, 1)# Dedup while keeping first-seen order (3.7+ dict order).
skus = ["A-1", "B-2", "A-1", "C-3"]
unique = list(dict.fromkeys(skus))
print(unique) # ['A-1', 'B-2', 'C-3']# Group anagrams.
from collections import defaultdict
words = ["eat", "tea", "tan", "ate"]
groups = defaultdict(list)
for word in words:
groups[tuple(sorted(word))].append(word)
print(sorted(groups.values()))Common Gotchas
Using a list as a key
`TypeError: unhashable type: 'list'`. Use a tuple or `frozenset`.
`x in list` inside a loop
build a set. The bug looks like "Python is slow", not like O(n²).
Mutable keys that change after insert
the dict cannot find them. Frozen data only.
`dict.fromkeys` is the ordered unique idiom
`set` loses order.