How convert list to nested dictionary?

macm moura.mario at gmail.com
Fri Nov 5 12:41:36 EDT 2010


Hi Folks

thanks a lot all. All solutions work fine.

while I am doing my home work.
Reading "Learning Python" and much more.

Let me ask again to close my doubts:

>>> l = ['k1', 'k2', 'k3', 'k4', 'k5']
>>> d = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
>>> d
{'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3]}}}}}}
>>> d['k1']['k2']['k3']['k4']['k5']
{'/': [1, 2, 3]}
>>> d['k1']['k2']['k3']['k4']['k5']['/']
[1, 2, 3]
>>>

now I want generate the "index" to access the element.

==> d['k1']['k2']['k3']['k4']['k5']['/'] from l

So again I have only.
>>> l = ['k1', 'k2', 'k3', 'k4', 'k5']

z = ?magicCode?

z = d['k1']['k2']['k3']['k4']['k5']['/']

>>> z
[1, 2, 3]
>>>z.append('4')
>>>z
[1, 2, 3, 4]

Best Regards

macm



On 5 nov, 11:57, Peter Otten <__pete... at web.de> wrote:
> Boris Borcic wrote:
> > Arnaud Delobelle wrote:
> >> macm<moura.ma... 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