Last active
May 10, 2018 12:31
-
-
Save g-io/ce805010d5bde3e42307f5f256e101e3 to your computer and use it in GitHub Desktop.
Python autovivified nested dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It throws me an error
AttributeError: 'Vividict' object has no attribute 'rec_dictify'
when I call
dictify()
function