How convert list to nested dictionary?

Peter Otten __peter__ at web.de
Fri Nov 5 09:57:18 EDT 2010


Boris Borcic wrote:

> Arnaud Delobelle wrote:
>> macm<moura.mario at gmail.com>  writes:
>>
>>> Hi Folks
>>>
>>> How convert list to nested dictionary?
>>>
>>>>>> l
>>> ['k1', 'k2', 'k3', 'k4', 'k5']
>>>>>> result
>>> {'k1': {'k2': {'k3': {'k4': {'k5': {}}}}}}
>>>
>>> Regards
>>>
>>> macm
>>
>> reduce(lambda x,y: {y:x}, reversed(l), {})
>>
> 
> d={}
> while L : d={L.pop():d}

Iterating over the keys in normal order:

>>> keys = "abcde"
>>> d = outer = {}
>>> for key in keys:
...     outer[key] = inner = {}
...     outer = inner
...
>>> d
{'a': {'b': {'c': {'d': {'e': {}}}}}}

The "functional" variant:

>>> d = {}
>>> reduce(lambda outer, key: outer.setdefault(key, {}), "abcde", d)
{}
>>> d
{'a': {'b': {'c': {'d': {'e': {}}}}}}

In a single expression if you are willing to pay the price:

>>> reduce(lambda (accu, outer), key: (accu, outer.setdefault(key, {})), 
"abcde", ({},)*2)[0]
{'a': {'b': {'c': {'d': {'e': {}}}}}}

Peter



More information about the Python-list mailing list