Tuesday 15 March 2011

Recursively traversing Python dictionary and removing keys

Code Snippet to recursively traverse a dictionary and remove certain key/value pair

In case of complex dictionaries like
my_blog = { '_created' : datetime.datetime (2007,01,03),
          '_updated' : datetime.datetime (2011,06,11),
            'name'     : 'MyBLive',
            'latest_post'    : { '_created' : datetime.datetime (2007,06,9),
                                 '_updated' : datetime.datetime (2007,069),
                                 'name'     : 'Hello World !' }

The problem with this is that datetime.datetime entities are not JSON Serializable. One approach could be to provide a serializer for datetime.datetime entities as suggested by verte over IRC. If you want to have a datetime.datetime aware JSONSerializer, you should have a look at the django.core.serializers.json module

In my case, we were using a Google App Engine application and the JSON response need not contain these key/value pairs so it makes more sense if these are removed from the dictionary.

def rm (d, l):
  Removed from dictionary "d" all those key-value pairs the keys of which
  are defined as a list in "l"
  if not l: return d
  if reduce ( lambda x,y: x or y, [x in d.keys () for x in l]):
    [d.pop (x, None) for x in l]
  [rm (x, l) for x in d.values () if isinstance (x, dict)]
  return d

No comments:

Post a Comment