Building and Transvering multi-level dictionaries

Lee Joramo ljoramo at
Tue Mar 21 01:53:12 CET 2000

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.

For example, say that I have a file sample.dat with the line format:

catagory:sub:sub TAB description

---start sample.dat----
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
---end sample.dat---

The first part of each line is the items classification. The number of
sub-catagories is variable.

>From this file I want to generate a python dictionary:

{'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'}}}

Then I want to be able to transvers the dictionary and print an outline:

       * A very lazy dog
       * Super hunting dog
       * Not your average hound
       * Enjoys sleeping in the sun
       * Beware of the python in the forest
       * There are many fish in the deep blue sea
       * Tuna terrorize the oceans
       * Very Very Very Tall
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 = ''
description = mydict[compoundkey] 

Thanks for any suggestions.

Lee A. Joramo                      ljoramo at
The Nickel Want Ads      
Internet Manager                   970-242-5555

More information about the Python-list mailing list