I have been trying to implement autovivification for python dictionary. I have referred the following links as well which has helped me to achieve what I wanted, but partially.
What is the best way to implement nested dictionaries?
How to implement autovivification for nested dictionary ONLY when assigning values?
This is the example I have been trying for my purpose
class MyDict(dict):
def __setitem__(self, keys, value):
if not isinstance(keys, tuple):
return dict.__setitem__(self, keys, value)
for key in keys[:-1]:
self = self.setdefault(key, {})
dict.__setitem__(self, keys[-1], value)
This is working for normal cases such as
my_dict = MyDict()
my_dict['a','b','c']=10
which results in : {'a': {'b': {'c': 10}}}
But how do i implement this which is very much possible with collections.defaultdict
my_dict['a']['b']['c'].append(10)
I don't want to implement defaultdict because of it's non-human-readable output and moreover it is not working with pickle.
Any suggestion would be appreciated.
Thank you