Get Nested Dict Value with Default in Python

Access values deep inside a nested dictionary using a dotted path string, returning a default when any key is missing.

Medium Python 3.9+ Aug 9, 2026 Dictionaries & sets 16 views 0 copies

Python code

26 lines
Python 3.9+
def get_nested(d, path, default=None):
    """Walk a nested dict along a dotted path, returning default if missing."""
    current = d
    for key in path.split("."):
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    return current


if __name__ == "__main__":
    data = {
        "user": {
            "profile": {
                "name": "Alice",
                "age": 30
            },
            "settings": {"theme": "dark"}
        }
    }

    print(get_nested(data, "user.profile.name"))          # Alice
    print(get_nested(data, "user.profile.email"))         # None
    print(get_nested(data, "user.settings.theme"))        # dark
    print(get_nested(data, "user.missing.path", "N/A"))   # N/A

Output

stdout
Alice
None
dark
N/A

How it works

The split(".") call breaks the path string into individual keys, and the loop walks through the dictionary level by level. Each iteration checks that the current value is a dict and that the key exists before advancing, which prevents KeyError or TypeError on malformed paths. If any step fails, the function immediately returns the default. This pattern is safe and concise — no recursive calls or exception handling are required.

Common mistakes

  • Using `current[key]` without checking if the key exists, which raises a KeyError instead of returning the default.
  • Forgetting to verify `isinstance(current, dict)` — if a path leads to a list or string and you try `key in current`, you may get unexpected behavior.
  • Assuming the path separator is always `.` — hard-coding it means paths with dots inside keys break.
  • Returning `None` as the default and then confusing a legitimate `None` value in the data with a missing key.

Variations

  1. Use `functools.reduce` with `dict.get` to walk the path in a single expression.
  2. Accept a list of keys instead of a dotted string, e.g., `get_nested(data, ['user', 'profile', 'name'])`.

Real-world use cases

  • Reading configuration values from deeply nested YAML or JSON settings files in a service bootstrap.
  • Extracting specific fields from large API responses without writing nested try/except or chained `.get()` calls.
  • Checking optional feature flags stored in hierarchical user preferences or tenant configurations.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.