Recursive update of arbitrarily nested dicts
maxm
maxm at mxm.dk
Sat Dec 15 12:07:07 EST 2001
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
oh and self.tracks={}
But clearly this could be solved more generally by a recursive function.
Something like:
def addDayToTrack(self, trackId, year, theDay, day):
# recursive update
self.rUpdate(self.tracks, {trackId:{year:{theDay:day}}})
Now my only problem is that recursive method "rUpdate(targetDict,
itemDict)".
Knowing this group, many other has written a method like this before me.
Does anybody have one at hand?
The idea is that it should traverse the targetDict, updating keys and values
as apropriate.
Anyhoo ... I will try it myself, but recursion is not my pot of tea though.
regards Max M
More information about the Python-list
mailing list