Recursive update of arbitrarily nested dicts

maxm maxm at mxm.dk
Sun Dec 16 05:42:43 EST 2001


"Jason Orendorff" <jason at jorendorff.com> wrote in message
news:mailman.1008452899.18809.python-list at python.org...
> > I am writing a module where I am updating nested dicts, and it has this
> > method:
> >
> >     def addDayToTrack(self, trackId, year, theDay, day):
> >         if not self.tracks.has_key(trackId):
> >             self.tracks.update({trackId:{year:{theDay:day}}})
> >         elif not self.tracks[trackId].has_key(year):
> >             self.tracks[trackId].update({year:{theDay:day}})
> >         elif not self.tracks[trackId][year].has_key(theDay):
> >             self.tracks[trackId][year][theDay] = day
>
>   def addDayToTrack(self, trackId, year, theDay, day):
>       """ Not the recursive solution you're seeking, but better anyway """
>       trackDict = self.tracks.setdefault(trackId, {})
>       yearDict = trackDict.setdefault(year, {})
>       yearDict[theDay] = day


That was a _much_ nicer solution than my own, and pretty clever too. I did
know the setdefault() method, but it would never have occured to me to use
it like that. All in all it gave me a good push in the right direction to a
recursive version::

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

And event though your version is in fact simpler than the recursive one, I
think I will keep the recursive one in my toolbox as it's more general.

Thanks!

regards Max M





More information about the Python-list mailing list