Skip to content

Instantly share code, notes, and snippets.

@afirth
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afirth/9b10ce1efb3b3a123fe5 to your computer and use it in GitHub Desktop.
Save afirth/9b10ce1efb3b3a123fe5 to your computer and use it in GitHub Desktop.
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