Write to dictionary using list-path

Viewed 79

I would like to write to a dictionary with a 'list-path'. I have:

container = {}
path = ['foo', 'bar']
data = [1, 2, 3]

And would like to get

container = {
    'foo' : {
        'bar' : [1, 2, 3]
    }
}

To read, I am very enthusiastic about this answer, which says that to read:

data = functools.reduce(operator.getitem, path, container)

But now I'm not managing to get the opposite right...

(I guess one could use recursion, but a one-line solution seems near!)

1 Answers

This isn't a one liner, but I changed this answer a bit so it would add the data to the last element.

path = ['foo','bar']
data = [1,2,3]
container = {}
for key in reversed(path):
    if (key == path[-1]):
        container = {key: data}
    else:
        container = {key: container}

This is the output: {'foo': {'bar': [1, 2, 3]}}

Edit: Nevermind, I found a one liner based on this answer

import functools
path = ['foo','bar']
data = [1,2,3]
container = functools.reduce(lambda x,y:{y:x},path[:-1],{path[-1]: data})
Related