Skip to content

Instantly share code, notes, and snippets.

@baopham
Created April 18, 2012 17:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baopham/2415372 to your computer and use it in GitHub Desktop.
Save baopham/2415372 to your computer and use it in GitHub Desktop.
Python Autovivification
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
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}}}
@baopham
Copy link
Author

baopham commented Apr 18, 2012

source: Stack Overflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment