Skip to content

Instantly share code, notes, and snippets.

Created November 3, 2015 06:50
What would you like to do?
different implemention of nested dict in Python
#!/usr/bin/env python
# different implemention of nested dict in Python
from collections import defaultdict
# from:
class AutoVivification(dict):
def __getitem__(self, item):
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
# from:
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# from:
def ddict():
return defaultdict(ddict)
# from @lpp1985
class Ddict(defaultdict, dict):
def __init__(self):
defaultdict.__init__(self, Ddict)
def __repr__(self):
return dict.__repr__(self)
# test
for c in [AutoVivification, Vividict, ddict, Ddict]:
print("\n%s\n%s" % ('=' * 78, c))
d = c()
d[1][2][3] = 4
d['a']['b']['c'] = 'd'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment