Building and Transvering multi-level dictionaries

Justin Sheehy dworkin at
Fri Mar 31 16:58:20 CEST 2000

"maxm" <maxm at> writes:

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

You could certainly write a recursive function to gather all of the
keys, and I was about to do so... but I decided that it wasn't worth
the work.  Instead, just make a couple of small changes to the class.

(I'm only showing the methods that changed)

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

    def keys(self):
        return self._keys[:]

    def insert(self, keys, value): 
        if not keys: 
            if not self.children.has_key(keys[0]): 
                self.children[keys[0]] = MyTree() 
            self.children[keys[0]].insert(keys[1:], value) 

Just one line added to __init__ and insert, and you can write a
trivial keys() method.  Enjoy!



More information about the Python-list mailing list