Skip to content
GreenSnippets

Safely read a deeply nested value

Walk a path through nested dicts and lists and return a default instead of raising KeyError.

Python
def get_path(data, path, default=None):
    current = data
    for part in path:
        try:
            current = current[part]
        except (KeyError, IndexError, TypeError):
            return default
    return current

Example / expected output

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.