list -> dict help

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Mon Jan 31 12:46:38 EST 2000


Bill Scherer wrote in comp.lang.python:
> What's the best way for me to do this:
> 
> say I have a list:
> 
> >>> l = ['a', 'b', 'c', 1]
> 
> and I want to turn it into a dictionary that looks like this:
> 
> >>> print d
> {'a': {'b': {'c': 1}}}
> 
> where the length of list l is >= 3.
> 
> Basically, list[:-2] represents the nested keys, list[-2] is a terminal
> key, and list[-1] is the value.
> 
> It seems I need somthing to recur over list[:-2], then add the terminal
> info but I can't figure it out...

The first thing I thought of was recursion. Something cute like:

def convert(l):
    if len(l) == 1:
	   return l[0]
	else:
	   return { l[0] : convert(l[1:]) }
	   
But this copies the list every call, and recursion can use a lot of stack.
Since it's tail recursion, there must be an iterative version.

The following one works, but I don't really like it. References
are weird in cases like this. I hope it's understandable.

def convert(list):
    d = { list[0] : None } # Initialize with the first key
    lastdict = d       # Remember which dict to change and with which key,
    lastkey = list[0]  # so the 'None' can be replace in the loop.
    
    for key in list[1:-1]:
        subdict = { key : None }
	    lastdict[lastkey] = subdict
	
	    lastdict = subdict
	    lastkey = key
	
    # Add the last key
    lastdict[lastkey] = list[-1]
	
    return d
	
	
-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!



More information about the Python-list mailing list