Building and Transvering multi-level dictionaries

maxm maxm at normik.dk
Fri Mar 31 07:00:38 EST 2000


> Justin Sheehy Wrote

> 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)


Thank you for the above code. I am using it to build a generic tree class.

I have one problem though. I am trying to make a keys() method, that will
give me a list of the 'keys' in the tree.

that way I will be able to do something like this:

#######################################3

theTree = MyTree()
theTree.insert(['me'], 'max')
theTree.insert(['me','child_1'], 'magnus')
theTree.insert(['me','child_2'], 'caroline')
theTree.insert(['me','child_3'], 'clara')

theKeys = theTree.keys()

for key in theKeys:
    print theTree.get_1(key)

>>>max
>>>magnus
>>>caroline
>>>clara

print theKeys
>>> [[me],['me','child_1'],['me','child_2'],['me','child_3']]

#######################################

I'm in recursion hell here and have been trying to wring out the keys for
almost two days now and can no longer think straight. :-)

Has anybody got an idea?

Max M

------------------------------------------------------------------------
Max M Rasmussen,   New Media Director    http://www.normik.dk   Denmark
e-mail  mailto:maxm at normik.dk    private mailto:maxmcorp at worldonline.dk
 Prosperity        thru        innovation        and        automation>






More information about the Python-list mailing list