Quick Answer
Safely handle missing dictionary keys.
Understanding the Issue
KeyError occurs when accessing non-existent dictionary keys. Unlike some languages, Python doesn"t return null/None. Explicit handling prevents unexpected failures in data processing pipelines.
The Problem
This code demonstrates the issue:
Python
Error
config = {"theme": "dark"}
print(config["color"]) # Fails
The Solution
Here's the corrected code:
Python
Fixed
# Solution 1: get() with default
color = config.get("color", "light")
# Solution 2: setdefault
color = config.setdefault("color", "light")
# Solution 3: collections.defaultdict
from collections import defaultdict
settings = defaultdict(lambda: "default")
value = settings["missing"]
Key Takeaways
Prefer get() or defaultdict for safe dictionary access.