Algorithmshashmap

Hash Maps in Python (dict as a Map)

TT
Testlaa Team
May 14, 20261 min read

In Python the workhorse hash map is dict: insertion, lookup, and deletion average O(1). Pair it with sets when you only need keys without satellite data.

Why this shows up in the real world

JSON objects, memoization tables, and graph adjacency with weights all map naturally to dicts.

Core idea (explained for students)

Iterate for k,v in d.items(), copy with dict(d) or {**d}, merge with d | e (3.9+). Use dict comprehensions for derived views.

Try this in Python

from collections import defaultdict


dd: dict[str, list[int]] = defaultdict(list)
for i, ch in enumerate('abca'):
    dd[ch].append(i)
print(dict(dd))

Common mistakes

  • Mutating dict while iterating causes RuntimeError—collect keys first.
  • Default missing: d[k] vs d.get(k).

Key takeaways

  • collections.ChainMap stacks dicts read-only style.
  • Prefer setdefault sparingly; defaultdict clearer for counts.

Tags:

Hashing & frequencyPythonStudents