Recursive update of arbitrarily nested dicts

maxm maxm at mxm.dk
Sun Dec 16 05:08:25 EST 2001


"Ype Kingma" <ykingma at accessforall.nl> wrote in message
news:3C1B9E80.FB732387 at accessforall.nl...

> In this case there is only one smaller problem, and there is no
> solution to be assembled from the solutions to the smaller problem.
> (warning: untested code)
>
> def rUpdate(nestedDict, keys, value): # keys should be a tuple or a list
>     firstKey, remainingKeys = keys[0], keys[1:] # divide the problem
>     if len(remainingKeys) == 0: # non recursive case
>         # Evt. raise an exception when nestedDict[firstKey] is a dict
>         nestedDict[firstKey] = value # actual update.
>     else:
>         if not nestedDict.has_key[firstKey]: # make sure there is sub dict
to recurse on
>             nestedDict[firstKey] = {}
>         rUpdate(nestedDict[firstKey], remainingKeys, value) # recurse on
smaller problem.

whoa ... thats a pretty complex solution. I was hoping for something a bit
simpler ;-)

In fact I do belive that I have found it myself, after an hour of fun. ;-)

    def rUpdate(self, targetDict, itemDict):
            for key, val in itemDict.items():
                if type(val) == type({}):
                    newTarget = targetDict.setdefault(key,{})
                    self.rUpdate(newTarget, val)
                else:
                    targetDict[key] = val

I allways find it amusing that recursive functions in Python ends up so
relatively simple, even though I usually have a bit of a problem finding the
right solution.

I have read somewhere that thinking in pointers is something a programmer
either can or cannot do. I have no trouble with pointers. But perhaps it's
the same with recursion ... I don't know. I can usually find a solution, but
it often takes me far to long. I guess if I do it more I will get better at
it. Perhaps I should study some Lisp to get some more experience in it.

Anyhoo ... Thanks for the answer.

regards Max M





More information about the Python-list mailing list