Topic 50 of 64
Dictionary
Overview
Beyond basic access, Python dicts have rich methods for safe lookups, bulk access, and combined update operations. Knowing these prevents KeyError bugs and makes code more concise.
Syntax
python
d = {"a": 1, "b": 2, "c": 3}
# Keys, values, items
d.keys() # dict_keys(['a', 'b', 'c'])
d.values() # dict_values([1, 2, 3])
d.items() # dict_items([('a', 1), ('b', 2), ('c', 3)])
# setdefault — get or set default
d.setdefault("d", 0) # adds "d":0 if missing, returns value
# update — merge dicts
d.update({"e": 5, "f": 6})
# Python 3.9+ merge operator
merged = d | {"g": 7}
# pop with default
val = d.pop("z", None) # None (no KeyError)Common Pitfalls
- d.items(), d.keys(), d.values() return view objects (not lists) — they reflect changes to the dict dynamically.
- Iterating over a dict and modifying it simultaneously raises RuntimeError — iterate over a copy: list(d.items()).
- Interview tip: Use collections.defaultdict to avoid setdefault boilerplate: defaultdict(list) auto-creates empty list for missing keys.
Real-World Example
Building a config registry with setdefault and get patterns
example
python
def get_config(config: dict, key: str, default=None):
return config.get(key, default)
def merge_configs(base: dict, override: dict) -> dict:
return base | override # Python 3.9+
base = {"host": "localhost", "port": 5432, "debug": False}
override = {"port": 5433, "debug": True}
final = merge_configs(base, override)
print(final)
# {'host': 'localhost', 'port': 5433, 'debug': True}