Dictionaries
Dictionary Methods
get, keys, values, items, update
Interview: Essential methods — tests understanding of dict views and safe access patterns
Dictionaries provide a rich set of methods for access, modification, and iteration. Key concepts include view objects (keys(), values(), items()) that reflect live changes, safe access patterns (get, setdefault), and bulk operations (update, merge).
Access Methods
- get(key, default): Safe access — returns default if key missing (None by default)
- setdefault(key, default): Returns value if key exists; otherwise sets and returns default
- keys(): View of all keys (live, reflects changes)
- values(): View of all values
- items(): View of (key, value) tuples — most common for iteration
Modification Methods
- update(other): Merge key-value pairs from another dict/iterable
- | operator (3.9+):
d1 | d2creates new merged dict - |= operator:
d1 |= d2in-place merge - pop(key, default): Remove and return value
- popitem(): Remove and return last (key, value) pair (LIFO in 3.7+)
- clear(): Remove all items
View Objects
keys(), values(), and items() return view objects — dynamic windows into the dictionary. They update when the dict changes, support set operations (keys and items), and are more memory-efficient than creating lists.
setdefault vs defaultdict
setdefault() evaluates the default value every time it's called, even if the key exists. For expensive defaults, use collections.defaultdict instead.
Use Cases
Safe data access without try/except blocks
Iterating and transforming key-value data
Building layered configuration systems
Grouping data by key (with setdefault or defaultdict)
Common Mistakes
Using setdefault() with expensive defaults (evaluates even when key exists — use defaultdict)
Forgetting that view objects are live (they change when the dict changes)
Not knowing that popitem() is LIFO in Python 3.7+ (not random like pre-3.7)
Trying to modify dict during iteration over items() (RuntimeError: dictionary changed size)