How convert list to nested dictionary?

macm moura.mario at gmail.com
Fri Nov 5 15:40:35 EDT 2010


Ok. Done


>>> def appendNested(nest, path, val):
...     nest2 = nest
...     for key in path[:-1]:
...         nest2 = nest2[key]
...     nest2[path[-1]].append(val)
...     return nest
...
>>>
>>> l = ['k1','k2','k3','k4','k5']
>>> ndict = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
>>> x = l + list('/')
>>> print appendNested(ndict, x, 5)
{'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3, 5]}}}}}}
>>>


I need make lambda but now is friday night here and I guess I will go
drink a beer or three!

Cheers!

macm


On 5 nov, 16:51, macm <moura.ma... at gmail.com> wrote:
> Hi Peter
>
> Thanks a lot for your tips and codes,
>
> Cake Recipes are good to learn! So I post just basic issues.
>
> Hopping a good soul like you can help me!
>
> But I am still learning... : )
>
> Best Regards
>
> macm
>
> On 5 nov, 15:40, Peter Otten <__pete... at web.de> wrote:
>
> > macm wrote:
> > > 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']['/']
>
> > You'll eventually have to start and write your first line of code. Why not
> > doing it right now? It is sure more rewarding than copying other people's
> > canned solutions and it can even be fun.
>
> > Peter
>
>




More information about the Python-list mailing list