Created
May 6, 2011 18:49
-
-
Save MichaelBlume/959534 to your computer and use it in GitHub Desktop.
deepdict: quickly create highly nested dictionary structures without lots of initialization steps.
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
'''deepdict: quickly create highly nested dictionary structures without lots | |
of initialization steps.''' | |
from collections import defaultdict | |
class deepdict(defaultdict): | |
def __init__(self, *a, **kw): | |
defaultdict.__init__(self, deepdict, *a, **kw) | |
def __add__(self, num): | |
return num | |
def __str__(self): | |
return str(self.shallow) | |
@property | |
def shallow(self): | |
out = {} | |
for k, v in self.items(): | |
if isinstance(v, deepdict): | |
v = v.shallow | |
out[k] = v | |
return out | |
def main(): | |
foo = deepdict() | |
foo['bar']['baz']['qux'] += 5 | |
print foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment