Last active
August 29, 2015 14:01
-
-
Save afirth/9b10ce1efb3b3a123fe5 to your computer and use it in GitHub Desktop.
NestedDict
This file contains hidden or 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
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