How to Set Nested Dict Value Creating Missing Keys in Python
Set a value deep inside a nested dictionary, automatically creating any missing intermediate dicts along the path.
Python code
31 linesdef set_nested_value(d, keys, value):
"""
Set a value in a nested dict, creating missing intermediate keys.
Args:
d: The dict to modify
keys: Iterable of keys forming the path (e.g., ['a', 'b', 'c'])
value: The value to set at the final key
"""
current = d
for key in keys[:-1]:
# Create intermediate dict if key doesn't exist or isn't a dict
if key not in current or not isinstance(current[key], dict):
current[key] = {}
current = current[key]
current[keys[-1]] = value
if __name__ == "__main__":
# Example usage
data = {}
set_nested_value(data, ['users', 'alice', 'age'], 30)
set_nested_value(data, ['users', 'alice', 'email'], 'alice@example.com')
set_nested_value(data, ['users', 'bob', 'age'], 25)
set_nested_value(data, ['settings', 'theme', 'dark'], True)
# Add nested value with existing dict preserved
set_nested_value(data, ['users', 'alice', 'prefs', 'language'], 'en')
print(data)
# Expected: {'users': {'alice': {'age': 30, 'email': 'alice@example.com', 'prefs': {'language': 'en'}}, 'bob': {'age': 25}}, 'settings': {'theme': {'dark': True}}}
Output
{'users': {'alice': {'age': 30, 'email': 'alice@example.com', 'prefs': {'language': 'en'}}, 'bob': {'age': 25}}, 'settings': {'theme': {'dark': True}}}
How it works
The helper iterates over every key except the last one, climbing down the nested structure. For each intermediate step, it creates an empty dict if the key is missing or holds a non-dict value, then moves into it. The final line assigns the value to the last key. This in-place mutation means the original dict is updated directly, making the function handy for incrementally building config or data structures.
Common mistakes
- Forgetting that the function modifies the dict in place, so assigning the result to a new variable won't work.
- Passing an empty keys list, which causes a KeyError since keys[-1] fails.
- Assuming all intermediate values are dicts; the isinstance check is necessary to avoid overriding existing non-dict data.
- Not handling the case where a key exists but holds a non-dict value, leading to a TypeError when trying to add a sub-key.
Variations
- Use a recursive function that splits the path into head and tail, walking down and rebuilding the structure.
- Leverage a defaultdict from collections to auto-create nested levels, though it requires wrapping at every depth.
Real-world use cases
- Building a nested configuration object from flattened API parameters before passing it to a service.
- Aggregating multi-level analytics data (e.g., by user, then date, then metric) without manual initialization.
- Storing hierarchical results from a crawler or scanner, where each discovered path extends the tree on the fly.
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.