Skip to content

Instantly share code, notes, and snippets.

@xamox
Created November 10, 2011 04:22
Show Gist options
  • Save xamox/1354108 to your computer and use it in GitHub Desktop.
Save xamox/1354108 to your computer and use it in GitHub Desktop.
This is useful for setting nested dictionaries and setting items like objects
class AutoVivification(dict):
"""
Implementation of perl's autovivification feature.
>>> a = AutoVivification()
>>> a[1][2][3] = 4
>>> a[1][3][3] = 5
>>> a[1][2]['test'] = 6
>>> print a
>>> {1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}
"""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment