Patternite Logo

Automatically create nested dictionaries with Python defaultdict

1

Nesting dictionaries in Python can be verbose. Using a recursively defined `defaultdict` automatically creates nested dictionaries as required.

Loading...

Here we use defaultdict from the built-in collections module, which you can read more about here. A function can be passed to defaultdict which will be invoked to create a default value whenever a key that doesn't exist is accessed. In our case, we define a recursive version of defaultdict, which will create a new defaultdict value. This allows us to arbitrarily nest dictionaries, without having to manually create a new dictionary at each level. recursive_defaultdict is especially useful in instances where keys are being added to a dictionary in a nested for loop:

nested_dict = recursive_defaultdict()
for key_1, value_1 in some_data.items():
    for key_2, value_2 in value_1.items():
        for key_3, value_3 in value_2.items():
            nested_dict[key_1][key_2][key_3] = value_3

rather than a regular dict, where we would have to create a new dictionary at each level:

nested_dict = {}
for key_1, value_1 in some_data.items():
    nested_dict[key_1] = {}
    for key_2, value_2 in value_1.items():
        nested_dict[key_1][key_2] = {}
        for key_3, value_3 in value_2.items():
            nested_dict[key_1][key_2][key_3] = value_3
Profile picture for duncster

Patternite © 2021

Patternite Logo