1. Dictionary Lookups and .get()
Avoiding KeyError with Defaults
- Accessing a nonexistent key via bracket syntax `d[key]` raises a KeyError.
- The `.get(key, default)` method returns `None` (or your chosen fallback) if the key is not found, preventing crashes.
- The `setdefault(key, default)` method returns the value if present, or inserts and returns default if absent.
counts = {"apple": 5}
# print(counts["banana"]) -> Raises KeyError!
print("Banana count:", counts.get("banana", 0))
💡 Key Takeaway: Use `.get()` when a key might be missing and you have a sensible default.