Building and Transvering multi-level dictionaries

Justin Sheehy dworkin at ccs.neu.edu
Fri Mar 31 09:58:20 EST 2000


"maxm" <maxm at normik.dk> 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): 
        self._keys.append(keys)
        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) 

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

-Justin

 




More information about the Python-list mailing list