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.
Python code
26 linesdef 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
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
- Use `functools.reduce` with `dict.get` to walk the path in a single expression.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.