Safely read a deeply nested value
Walk a path through nested dicts and lists and return a default instead of raising KeyError.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
def get_path(data, path, default=None):
current = data
for part in path:
try:
current = current[part]
except (KeyError, IndexError, TypeError):
return default
return currentExample / expected output
get_path({"user": {"emails": ["a@x.io"]}}, ["user", "emails", 0]) # 'a@x.io'
get_path({}, ["user", "name"], "anonymous") # 'anonymous'How it works
API responses often have optional nesting. A path helper keeps lookups readable and avoids chains of .get() calls. Integer path parts index lists; everything else is a dict key.
Related snippets
- Python Tested
Group items by a key
Collect a list of records into a dictionary of lists keyed by a field or function result.
- Python Tested
Flatten a nested dictionary
Turn nested dicts into a single-level dict with dotted keys, handy for config and logging.
- TypeScript Tested
Parse JSON into a typed value with a guard
Safely turn unknown JSON into a typed result by validating its shape instead of casting.
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.

