list -> dict help

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Tue Feb 1 08:23:22 EST 2000


Bill Scherer wrote in comp.lang.python:
> Thanks! This works almost perfect.  My only problem now is that of course I'm
> dealing with many lines of input, and I want to put them all in the same
> dictionary. (sorry for not mentioning this originally).  eg:
> 
> I'll have many lists that are functionally equivalent to the following:
> 
> ['a', 'b', 'c', 1]
> ['a', 'b', 'r', 21]
> ['a', 'g', 'e', 'z', 13]
> etc...
> 
> my earlier statement, that l[:-2] are netsed keys and l[-2:] is the terminal
> key/value pair, still holds.

So that would result in a dictionary such as the following?
{'a' : {'b' : {'c' : 1, 'r' : 21}, 'g' : { 'e' : {'z': 13 }}}}

The following should work then (expanded from the previous answer):

#!/usr/local/bin/python

def convert(list):
    d = { list[0] : None }
    lastdict = d       # Remember which dict to change with which keys,
    lastkey = list[0]  # for replacing the None.
    
    for key in list[1:-1]:
        lastdict[lastkey] = { key : None }
        lastdict = lastdict[lastkey]    

        lastkey = key
    
    # Add the last key
    lastdict[lastkey] = list[-1]
	
    return d

dict = {}

def add_list_to_dict(list):
    """
    Find the first place in the existing dictionary	where this list adds 
	something new. Put the 'convert' of the remainder of the list into 
	dict at that point.
	"""
    tempdict = dict
    for keynum in range(len(list)-1):
    try:
        tempdict = tempdict[list[keynum]]
    except KeyError:
        if keynum == len(list)-2:
            tempdict[list[keynum]] = list[keynum+1]
        else:
            tempdict[list[keynum]] = convert(list[keynum+1:])
        return


>>> add_list_to_dict(['a','b','c',1])
>>> add_list_to_dict(['a','b','r',21])
>>> add_list_to_dict(['a','g','e','z',13])
>>> dict
{'a': {'b': {'r': 21, 'c': 1}, 'g': {'e': {'z': 13}}}}

There is an undefined case, if a new list overlaps with an old list.
My code keeps the old value.

>>> dict = {}
>>> add_list_to_dict(['a','b','c',1])
>>> add_list_to_dict(['a','b','c',2])
>>> dict
{'a': {'b': {'c': 1}}}

Probably someone can improve on it, but it works for me :-). For production
code it needs better names and better bounds checking.

ObShouldHaveAskedThisEarlier: What do you need this for, anyway? Isn't
   there a simpler solution?

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
"This gubblick contains many nonsklarkish English flutzpahs, but the
 overall pluggandisp can be glorked from context"  (David Moser)



More information about the Python-list mailing list