Created
December 21, 2012 16:39
-
-
Save emiel/4353901 to your computer and use it in GitHub Desktop.
Recursively replace nested dict(s) with your own dict subclass type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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