How convert list to nested dictionary?

Arnaud Delobelle arnodel at gmail.com
Fri Nov 5 15:59:17 EDT 2010


Peter Otten <__peter__ at web.de> writes:

> 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

The most basic functional version:

>>> f = lambda l: {l[0]: f(l[1:])} if l else {}
>>> f('abcde')
{'a': {'b': {'c': {'d': {'e': {}}}}}}

-- 
Arnaud



More information about the Python-list mailing list