Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class NestedDict(dict):
def __getitem__(self, key):
if key in self: return self.get(key)
return self.setdefault(key, NestedDict())
# 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.