Back
+10 XP
Concept

Safe Access with `.get()`

`.get(key, default)` safely returns a value. If the key is missing, it hands you `None` (or your custom fallback) without crashing.

python
user = {"id": 404}
print(user.get("name"))          # None (no crash!)
print(user.get("role", "guest")) # guest (fallback)

# 80. Safe Access with `.get()` `.get(key, default)` safely returns a value. If the key is missing, it hands you `None` (or your custom fallback) without crashing: ```python user = {"id": 404} print(user.get("name")) # None (no crash!) print(user.get("role", "guest")) # guest (fallback) ``` In production web applications, user payloads and API responses are notorious for missing expected fields. `.get()` is your first line of defense against unexpected server 500 errors.

Checkpoint

What does `d.get('missing')` return if no fallback default is provided?

Practice

Safely retrieve key `"status"` from `server = {}` with a fallback value of `"offline"`. Print the result.

Terminal
01
Tap code blocks below to assemble
Available Blocks