0

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.

smci
  • 32,567
  • 20
  • 113
  • 146

3 Answers3

0

You're almost there, you just need to keep track of how far you are into the tree structure, and a way to know when you're on the last element of the path:

def add_value(path, value):
    tmp = data
    parts = list(path.split('.'))
    for i in range(len(parts) - 1):
        part = parts[i]
        if not part in tmp:
            tmp[part] = {}
        tmp = tmp[part]
    tmp[parts[-1]] = value
Isaac
  • 3,586
  • 1
  • 18
  • 20
0

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
JOHN_16
  • 616
  • 6
  • 12
0

you can try Raymond Hettinger recipe :

source: https://twitter.com/raymondh/status/343823801278140417

from collections import defaultdict

infinity_dict=lambda:defaultdict(infinity_dict)

d=infinity_dict()
d['root']['sub']['item'] = 12
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88