Python list for nested keys

Im trying to create / populate a nested dictionary from a list.

For example, a list [['a','b','c'],value]

can create:

data['a']['b']['c'] = value

      

Giving me a dictionary:

{ 'a': { 'b': { 'c' : value } } }

      

All help is greatly appreciated.

+2


source to share


3 answers


(Let's assume you have multiple pairs with multiple keys / values.)

You can use setdefault

to add nested dictionaries for the whole subkey if they don't already exist, continuing this new one each time for all but the last subkey. Then put the value in the innermost dict.

def add_nested(d, keys, value):
    for k in keys[:-1]:
        d = d.setdefault(k, {})
    d[keys[-1]] = value

      

Example:

values = [
    [['a','b','c'], 1],
    [['a','b','d'], 2],
    [['a','e','f'], 3]]

result = {}
for keys, value in values:
    add_nested(result, keys, value)
print(result)

      



Result:

{'a': {'b': {'c': 1, 'd': 2}, 'e': {'f': 3}}}

      


Alternatively, you can also use the good old infinite dictionary :

infinidict = lambda: collections.defaultdict(infinidict)
result = infinidict()
for keys, value in values:
    last = reduce(operator.getitem, keys[:-1], result)
    last[keys[-1]] = value

      

+3


source


Python:

l = [['a', 'b', 'c'], 'foo']
d = l[1]
for k in l[0][::-1]:
    d = {k : d}
print d

      



Output:

{'a': {'b': {'c': 'foo'}}}

      

+3


source


Use a generator and recursive style:

a = [
     [['a','b','c'],1],
     [['c','d'],1],
    ]

def l2d(a):
    def mkd(k,v):
        if not k:
            return v
        return {k[0]:mkd(k[1:],v)}
    for k, v in a:
        yield mkd(k,v)

for d in l2d(a):
    print d

      

Result:

>>> 
{'a': {'b': {'c': 1}}}
{'c': {'d': 1}}

      

0


source







All Articles