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] = 4a[1][3][3] = 5a[1][2]['test'] = 6print a
输出:
{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}


