Search code examples
pythonlogic

How can I create a dict of dicts in recursion with a provided list of keys


For example:

I need to create a dict of dicts when iterating over a list of keys

For example, I have this list

my_dict = {'root': {}}
my_keys = ['foo', 'bar', 'lorem', 'ipsum']

I wanna create a function to return this following dict

my_dict = {
    'root': {
        'foo': {
            'bar': {
                'lorem': {
                    'ipsum': {}
                }
            }
        }
    }
}

I think something using recursion, but I'm stucked in the logic.


Solution

  • With dict.setdefault function:

    curr_d = my_dict['root']
    for k in my_keys:
        curr_d = curr_d.setdefault(k, {})