Peter Otten <__pete...@web.de> writes:

> Boris Borcic wrote:
>
>> Arnaud Delobelle wrote:
>>> macm<moura.ma...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to