Search code examples
pythonpython-3.xdictionaryrecursiondefaultdict

Nested insertion/creation of dictionary


Given that you have an empty dictionary

data = {}

I have a path and a value

path = "root.sub.item"
value = 12

How could I recursively add objects that do not exist?

def add_value(path, value):
    for part in path.split('.'):
        if not part in data:
            data[part] = {}

The expected output for this would be:

data = {
    'root':{
        'sub':{
            'item': 12
        }
    }
}

Could somebody help out with this or point me in the right direction?
I'm using Python 3.6.


Solution

  • You can use some another kind of solution like recursive defaultdict, as in this answer.

    A quick and stupid example about how it can used:

    from collections import defaultdict
    
    def func(rdict, path, value):
        items = path.split('.')
    
        d = rdict[items[0]]
    
        for item in items[1:-1]:
            d = d[item]
    
        d[items[-1]] = value
    
    nested_dict = lambda: defaultdict(nested_dict)
    
    result = nested_dict()
    
    func(result, 'root.sub.item', 12)
    func(result, 'root.moon.value', 1)
    
    assert result['root']['sub']['item'] == 12
    assert result['root']['moon']['value'] == 1
    assert result['root']['moon']['noop'] != 0