Building and Transvering multi-level dictionaries

Justin Sheehy dworkin at ccs.neu.edu
Mon Mar 20 23:26:55 EST 2000


Lee Joramo <ljoramo at nickads.com> writes:

> However, I am looking for an method that can elegantly handel a
> dictionary with variable depth.

I usually wrap the dictionary in a class, and have it create
subdictionaries as needed.

A quick attempt at some code accomplishing what you describe is
appended to this message.

> Then I want to be able to transvers the dictionary and print an outline:
> 
> animal
>    mammal
>      dog
>        * A very lazy dog
>        * Super hunting dog
>        * Not your average hound
>      cat
>        * Enjoys sleeping in the sun
>      snake
>        * Beware of the python in the forest
>      fish
>        * There are many fish in the deep blue sea
>        * Tuna terrorize the oceans
> tree
>    evergreen
>      redwood
>        * Very Very Very Tall

My sample code prints the following.  I suspect that my output is
closer to what you want than is the sample output that you provided.  ;-)

>>> m = MyTree()
>>> m.populate('sample.dat')
>>> m.pprint()
animal
  fish
    * There are many fish in the deep blue sea
    * Tuna terrorize the oceans
  snake
    * Beware of the python in the forest
  mammal
    cat
      * Enjoys sleeping in the sun
    dog
      * A very lazy dog
      * Super hunting dog
      * Not your average hound
plant
  tree
    evergreen
      redwood
        * Very Very Very Tall

> compoundkey = 'animal.mammal.cat'
> description = mydict[compoundkey] 

My sample code allows the following:

>>> m.get('animal.mammal.cat')
['Enjoys sleeping in the sun']

Here is the code.  I hope that it helps you to move in the direction
that you seek.

-Justin

import string

class MyTree:
    def __init__(self):
        self.contents = []
        self.children = {}

    def populate(self, filename):
        for line in open(filename).readlines():
            if string.strip(line):
                splitline = string.split(line)
                keys = string.split(splitline[0], ':')
                value = string.strip(string.join(splitline[1:]))
                self.insert(keys, value)
    
    def insert(self, keys, value):
        if not keys:
            self.contents.append(value)
        else:
            if not self.children.has_key(keys[0]):
                self.children[keys[0]] = MyTree()
            self.children[keys[0]].insert(keys[1:], value)

    def get_1(self, keys):
        if not keys:
            return self.contents
        else:
            return self.children[keys[0]].get_1(keys[1:])

    def get(self, keystring):
        return  self.get_1(string.split(keystring, '.'))

    def pprint(self, indent=0):
        for value in self.contents:
            print '%s* %s' % (' ' * indent, value)
        for child in self.children.keys():
            print '%s%s' % (' ' * indent, child)
            self.children[child].pprint(indent+2)




More information about the Python-list mailing list