Skip to content

Instantly share code, notes, and snippets.

@emiel
Created December 21, 2012 16:39
Show Gist options
  • Save emiel/4353901 to your computer and use it in GitHub Desktop.
Save emiel/4353901 to your computer and use it in GitHub Desktop.
Recursively replace nested dict(s) with your own dict subclass type.
import json
from collections import defaultdict
class D(defaultdict):
def __init__(self, *args, **kwargs):
if args and len(args) == 1 and isinstance(args[0], dict):
for k, v in args[0].items():
if isinstance(v, dict):
self[k] = self.__class__(v)
else:
self[k] = v
else:
super(D, self).__init__(self.__class__, *args, **kwargs)
def __repr__(self):
return "D({})".format(dict.__repr__(self))
if __name__ == "__main__":
sample = json.JSONDecoder().decode('{"a": { "b": { "c": 1 } } }')
print(D(sample))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment