Python Dictionaries and Hash Table Tracing
Dictionaries are key-value mapping structures implemented as high-performance hash tables. Tracing dictionary updates, missing key handling (`.get()` vs bracket notation), and dictionary union operators (`|`) is critical for data transformation tasks.
Core Conceptual Insights
Theoretical Blueprint:A dictionary is like an office filing cabinet indexed by unique folder tabs. You can jump directly to tab `'Alice'` without flipping through folders from A to Z.
Common Developer Trap:Attempting to access a missing key using square brackets (`d['missing']`) raises `KeyError`, whereas `.get('missing')` safely returns `None`.
Structured Practice Breakdown
`dict.setdefault()` existing vs missing keys
user = {'role': 'admin'}
user.setdefault('role', 'guest')
user.setdefault('status', 'active')
print(user['role'], user['status'])admin activeExecution Walkthrough
Because `'role'` exists, `.setdefault('role', 'guest')` leaves `'admin'` intact. Because `'status'` is missing, `.setdefault('status', 'active')` inserts `'active'`. Output: `admin active`.
Numeric key hash equality (`1` vs `1.0` vs `True`)
d = {1: 'int', 1.0: 'float', True: 'bool'}
print(len(d), d[1])1 boolExecution Walkthrough
Because `1 == 1.0 == True` and all hash to `1`, Python treats them as ONE single key! Each subsequent assignment (`'float'`, `'bool'`) overwrites the previous value. `len(d)` is `1`, holding `'bool'`.
Dictionary union operator (`|` precedence)
base = {'a': 1, 'b': 2}
overrides = {'b': 99, 'c': 3}
res = base | overrides
print(res['b'], len(res))99 3Execution Walkthrough
Merging `base | overrides` updates `'b'` to `99` from `overrides` while preserving `'a': 1` and adding `'c': 3`. Output: `99 3`.
Iterating dictionary key modification error
data = {'x': 10, 'y': 20}
try:
for k in data:
if k == 'x':
data['z'] = 30
except RuntimeError:
print('Dictionary changed size')Dictionary changed sizeExecution Walkthrough
Adding `'z': 30` inside `for k in data:` triggers `RuntimeError: dictionary changed size during iteration`, which is caught and printed.