class AutoVivification(dict): “”“Implementation of perl’s autovivification feature.”“” def (self, item): try: return dict.(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}}}