# 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.

Subject: Python | Lesson 7 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/dictionaries
Previous: [Tuples & Sequence Unpacking](https://codewithanimation.in/python/tuples.md) | Next: [Sets & Mathematical Operations](https://codewithanimation.in/python/sets.md)

## 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():`.

## Common mistake: KeyErrors, Unhashable Types & Iteration Mutation

Attempting to use a mutable object (such as a `list` or another `dict`) as a key raises `TypeError: unhashable type: 'list'`. Keys must implement `__hash__()` and remain constant over their lifetime.

Crashing on missing keys: accessing `config['port']` directly in production code when `'port'` might be absent causes sudden runtime crashes. Always provide defaults with `.get()` or handle `KeyError`.

Never add or delete keys from a dictionary while actively looping over it. Python detects this and raises `RuntimeError: dictionary changed size during iteration`. To delete keys safely during a loop, iterate over a copy of the keys: `for k in list(d.keys()):`.

## Tip: Use collections.defaultdict for Grouping

When accumulating items into lists or counters by category, avoid clumsy `if key not in d: d[key] = []` boilerplate. Instead, import `collections.defaultdict(list)`. Accessing a missing key automatically initializes it to an empty list on the spot.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/dictionaries

## Check yourself

### Question 1

What happens when you execute `val = d["missing_key"]` on an empty dictionary `d = {}`?

- A. Python raises a KeyError exception.
- B. Python returns None quietly.
- C. Python creates the key with an empty string value.
- D. Python returns False.

Correct answer: A

Direct index lookup `d[key]` on an absent key immediately triggers `KeyError`. To return a default value instead of crashing, use `d.get(key, default)`.

- Why not B: Direct bracket indexing `d[k]` strictly raises KeyError on missing keys. Only `d.get(k)` returns None.
- Why not C: Reading a key never creates it. Only `d.setdefault()` or explicit assignment creates new entries.
- Why not D: Missing keys raise exceptions; they do not evaluate to boolean False.

### Question 2

Which of the following values can be used as a valid key in a Python dictionary?

- A. ("user", 1042) (a tuple containing only immutable objects)
- B. ["user", 1042] (a list)
- C. {"id": 1} (a dictionary)
- D. {1, 2, 3} (a set)

Correct answer: A

Dictionary keys must be hashable. Tuples containing only immutable objects are hashable and valid. Lists, sets, and other dictionaries are mutable and cannot serve as keys.

- Why not B: Lists are mutable and do not implement __hash__(), raising TypeError: unhashable type: 'list'.
- Why not C: Dictionaries are mutable and cannot be keys in another dictionary.
- Why not D: Sets are mutable. To use a set as a key, you must use frozenset({1, 2, 3}).

### Question 3

Since Python 3.7, what is guaranteed regarding dictionary iteration order?

- A. Items are guaranteed to iterate in the exact order they were inserted.
- B. Keys are automatically sorted in alphabetical or numerical ascending order.
- C. Iteration order is random and changes with every process restart due to hash randomization.
- D. Order is only preserved if the dictionary contains fewer than 8 keys.

Correct answer: A

Since Python 3.7, dictionaries are officially guaranteed to preserve insertion order. Iterating over keys, values, or items reflects the sequence in which keys were originally added.

- Why not B: Python dictionaries do not sort keys automatically. They preserve insertion order.
- Why not C: While hash salts randomize bucket positions, the separate dense entries table preserves insertion order deterministically.
- Why not D: Insertion order preservation is an unconditional language specification guarantee for dictionaries of all sizes.

## 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.
