How convert list to nested dictionary?

Peter Otten __peter__ at web.de
Fri Nov 5 13:40:40 EDT 2010


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