Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NestedDict
class NestedDict(dict):
def __getitem__(self, key):
if key in self: return self.get(key)
return self.setdefault(key, NestedDict())
#http://ohuiginn.net/mt/2010/07/nested_dictionaries_in_python.html retrieved 2014-05-09
#Credit (and thanks) to Dan O'Huiginn
#could also use __missing__ instead:
class NestedDict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
#arguably cleaner, but doesn't prettyprint nicely
Tree = lambda: defaultdict(Tree)
t = Tree()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.