Help with python dict

Posted on
Tue Jan 03, 2017 9:22 am
krissh offline
Posts: 105
Joined: Nov 18, 2012
Location: Norway

Help with python dict

Hi,

I don't quite understand why this doesn't work, so would appreciate it if someone could help me understand. I can do this a different way, but want to try to understand this :lol:

Code: Select all
def removeTriggerFromDict(d, triggerId):
   for k, v in d.iteritems():
      if isinstance(v, dict):
         v = removeTriggerFromDict(v, triggerId)
      elif k == u'triggers':
         tmpList = [t for t in v if t != triggerId]
         v = tmpList         
      else:
         raise ValueError(u'Possible error in triggerMap dictionary, v: %s' % unicode(v))
   return d


d is a nested dictionary, with a list of trigger ids some places, e.g.
Code: Select all
d[3][4][5][u'triggers'] = [123,456,789]
d[5][7][u'triggers'] = [123,789]


What I'm trying to do is remove all references to a trigger id, i.e.
Code: Select all
d = removeTriggerFromDict(d, 123)


would result in
Code: Select all
d[3][4][5][u'triggers'] = [456,789]
d[5][7][u'triggers'] = [789]


Thanks :)

Posted on
Tue Jan 03, 2017 12:53 pm
krissh offline
Posts: 105
Joined: Nov 18, 2012
Location: Norway

Re: Help with python dict

Googled a lot, seems like .iteritems() iterate over a copy of the dict, meaning that changing v will not change the dict. The following works well I think:

Code: Select all
def removeTriggerFromDict(d, triggerId):
   for k, v in d.iteritems():
      if isinstance(v, dict):
         d[k] = removeTriggerFromDict(v, triggerId)
      elif k == u'triggers':
         d[k] = [t for t in v if t != triggerId]
      else:
         raise ValueError(u'Possible error in triggerMap dictionary, v: %s' % unicode(v))
   return d

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 7 guests