PYTHON
Dynamically Creating Nested Dictionaries with defaultdict
Learn to efficiently create multi-level nested dictionaries in Python using collections.defaultdict, ideal for building flexible and sparse data structures without KeyErrors.
from collections import defaultdict
def create_nested_dict():
return defaultdict(create_nested_dict)
# Usage example:
nested_data = create_nested_dict()
# Accessing and assigning values automatically creates intermediate dictionaries
nested_data['user']['preferences']['theme'] = 'dark'
nested_data['user']['settings']['notifications'] = True
nested_data['products'][101]['name'] = 'Widget A'
nested_data['products'][101]['price'] = 29.99
print(f"User theme: {nested_data['user']['preferences']['theme']}")
print(f"Product 101 name: {nested_data['products'][101]['name']}")
# You can check the structure (note: it's a defaultdict, not a regular dict until converted)
# print(nested_data)
How it works: `collections.defaultdict` is a subclass of `dict` that calls a factory function to supply missing values. By recursively defining a `defaultdict` that returns another `defaultdict`, you can automatically create deeply nested dictionary structures on demand, preventing `KeyError` exceptions when accessing non-existent keys in a multi-level path. This is especially useful for building flexible data structures from dynamic inputs.