Building and Transvering multi-level dictionaries

Felix Thibault felixt at dicksonstreet.com
Tue Mar 21 08:37:12 CET 2000


At 17:53 3/20/00 -0700, Lee Joramo wrote:
>I am trying to build a multi-level dictionary from an text file, and
>then transverse the dictionary, create formated output. I have been
>able to do this for a special case where ever piece of data has a fixed
>number of levels (sub-catagories). However, I am looking for an method
>that can elegantly handel a dictionary with variable depth.
>

One way to do this is to make each sub-dictionary then use a function
like this to add it to your  big dictionary:

def adder(left, right):
    """adder(left, right) -> dictionary    merge two dicts"""
    out = left
    for key, value in right.items():
        if out.has_key(key):
            if type(out[key]) == type({}):
                out[key] = adder(out[key], value)
            elif type(out[key])==type([]):
                out[key].append(value)
            else:
                out[key] = [out[key], value]
        else:
            out[key] = value
    return out

So for the format you gave that's like:

---------------------------------------------------------------------
import string

testdata = """animal:mammal:dog             A very lazy dog
animal:mammal:dog             Super hunting dog
animal:mammal:dog             Not your average hound
animal:mammal:cat             Enjoys sleeping in the sun
animal:snake                  Beware of the python in the forest
animal:fish                   There are many fish in the deep blue sea
animal:fish                   Tuna terrorize the oceans
plant:tree:evergreen:redwood  Very Very Very Tall"""

datalist = string.split(testdata, '\n')

dict = {}
 
for line in datalist:
    	#break up this line and make the inside of this subdict...
	kvlist = string.split(line, ':')
	last = kvlist.pop()
	inside = string.split(last, '\t' , 1)
	tempdict = {string.strip(inside[0]): string.strip(inside[1])}
	
	#build up the rest of subdict from inside out...
	kvlist.reverse()
	for key in kvlist:
		tempdict = {key: tempdict}
	
	#...and add it to dict
	dict = adder(dict, tempdict)

and that dict is:

{'animal': {'fish': ['There are many fish in the deep blue sea',
                     'Tuna terrorize the oceans'],
            'mammal': {'cat': 'Enjoys sleeping in the sun',
                       'dog': ['A very lazy dog',
                               'Super hunting dog',
                               'Not your average hound']},
            'snake': 'Beware of the python in the forest'},
 'plant': {'tree': {'evergreen': {'redwood': 'Very Very Very Tall'}}}}

<snip>
>       
>Another point that I am interested in is how get a the value of a
>specific key in an easy way. For example, I know that I can get the
>value of 'cat':
>
>description = mydict['animal']['mammal']['cat'] 
>
>which in my example returns: 'Enjoys sleeping in the sun'
>
>However I am looking for a way of doing something like list:
>
>compoundkey = 'animal.mammal.cat'
>description = mydict[compoundkey] 

One way you could do this is like:

def retrieve(dict, compoundkey):
    temp = dict
    #(all your keys have to be strings to do this)
    for key in string.split(compoundkey, '.'):
        temp = temp[key]
    return temp

>
>Thanks for any suggestions.
>
>-- 
>--
>Lee A. Joramo                      ljoramo at nickads.com
>The Nickel Want Ads                www.nickads.com
>Internet Manager                   970-242-5555
>-- 
>http://www.python.org/mailman/listinfo/python-list
>
>

Felix





More information about the Python-list mailing list