Skip to content

Instantly share code, notes, and snippets.

@g-io
Last active May 10, 2018 12:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g-io/ce805010d5bde3e42307f5f256e101e3 to your computer and use it in GitHub Desktop.
Save g-io/ce805010d5bde3e42307f5f256e101e3 to your computer and use it in GitHub Desktop.
Python autovivified nested dictionary
class Vividict(dict):
"""
dict class which allows to set deeply nested values. Any nested dict will get autovivified.
Note that using defaultdict is more performant, so in case of huge datasets revert to that one.
However using this class and not 'closing' it after setting values might result in undesired behavior:
When accessing a value which is not set, no KeyError is thrown, instead it's autovivified into an empty Vividict.
To guarantee this doesn't happen but KeyError is thrown, dictify() needs to be called to transform the data structure
into regular dicts.
Usage example:
dict = Vividict()
dict['level1']['level2'] = 'value'
dict.dictify()
See https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries
"""
def __missing__(self, key):
value = self[key] = type(self)()
return value
def dictify(self):
self._rec_dictify(self)
def _rec_dictify(self, d):
for k, v in d.iteritems():
if isinstance(v, Vividict):
d[k] = self.rec_dictify(v)
return dict(d)
@Ostapp
Copy link

Ostapp commented May 10, 2018

It throws me an error
AttributeError: 'Vividict' object has no attribute 'rec_dictify'
when I call dictify() function

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