Learning navigation

Code with Animation

Dictionaries & Hash Maps

Master Python's core associative data structure, hash table mechanics, O(1) key lookups, insertion order guarantees, and defensive key access patterns.

Python7 min readConcept 7 of 24

Hash-Table Associative Mappings

A dictionary (dict) is an associative collection that maps unique, hashable keys to arbitrary values: user = {"id": 101, "name": "Alex"}.

Under the hood, Python dictionaries are implemented using high-performance open-addressing hash tables. Looking up, inserting, or deleting a key runs in O(1) average constant time.

Since Python 3.7 (originally introduced in CPython 3.6), dictionaries are officially guaranteed by the language specification to preserve insertion order. When you iterate over a dictionary, items yield in the exact order they were inserted.

The Compact Hash Table Architecture

Modern CPython splits the dictionary into two internal arrays: a sparse indices table of hash buckets, and a dense entries array holding [hash, key_ptr, value_ptr] structs in insertion order.

When a lookup occurs, Python computes hash(key). The hash integer determines the bucket index in the sparse table, which immediately points to the dense entry row holding the value.

Because the dense entries array is packed sequentially without holes, modern Python dictionaries use roughly 30% to 40% less memory than legacy hash table implementations.

Safe Access Patterns and Iteration

Direct indexing with brackets d[key] expects the key to exist. If the key is missing, Python raises an immediate KeyError.

To handle optional or missing keys safely, use d.get(key, default). If key is present, it returns the value; if missing, it returns default (which defaults to None) without throwing an exception.

Iterating over dictionaries: for key, value in d.items(): unpacks both keys and values cleanly. To inspect keys only, use for key in d:, and for values only, use for val in d.values():.

The Hash Table & KeyError Simulator

Select different keys and access methods. Watch how the hash function resolves keys to internal table rows, and compare the crash behavior of direct indexing against safe .get() fallbacks.

Select Key:
Method:
# 1. User dictionary:
user = {"user_id": 1042,
"role": "admin"}
# 2. Access expression:
val = user["role"]
# Result:
# "admin" (O(1) hit)
INTERNAL COMPACT ENTRIES TABLE (dict @ 0x7fd0)row: 0"user_id"→1042row: 1"role"→"admin"LOOKUP SUCCESSFUL: hash("role") → row 1VALUE RETRIEVED: "admin"O(1) constant-time direct memory accessKey matched hash bucket in dense entries array
★

Python Rule: Use d.get(key, default) whenever querying external payloads, request headers, or configurations where keys may be optional.

Python dictionaries look up keys in O(1) average constant time using compact internal hash tables.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens when you execute `val = d["missing_key"]` on an empty dictionary `d = {}`?
  2. 2Which of the following values can be used as a valid key in a Python dictionary?
  3. 3Since Python 3.7, what is guaranteed regarding dictionary iteration order?

Remember this

  • Dictionaries provide O(1) average key lookups, insertions, and deletions via hash tables.
  • Since Python 3.7, dictionaries strictly preserve insertion order.
  • Dictionary keys must be immutable and hashable (e.g. str, int, tuple).
  • Direct indexing d[k] raises KeyError if k is missing; d.get(k, default) safely returns a fallback.
  • Never modify dictionary keys while looping over it; iterate over list(d.keys()) instead.

Done with this concept?

Mark it complete to track your progress. No login needed.