Autogenerated Dictionary

In python, it’s often the case I find myself wanting the ability to very quickly construct dictionaries with nested structures. Unfortunately, the following use case is not easy to accomplish with python dictionaries used in the standard way:

dct = {}
dct['a'] = 1
dct['deep']['nested']['auto']['inferred']['structure'] = 2

print(dct)

"""
{
    'a': 1,
    'deep': {
        'nested': {
            'auto': {
                'inferred': {
                    'structure': 2,
                }
            }
        }
    },
}
"""

After a little bit of exploration with the python defaultdict collection, I found that this is easy enough to accomplish with some fun recursive trickery.

from collections import defaultdict
def reflect():
    return defaultdict(reflect)

dct = defaultdict(reflect) # Now works perfectly with the previous example