I am using some common python autovivification code build dictionaries:
class autoviv(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
One thing I'd love to be able to is to increment values in the case where no key currently exists at the specified dictionary nesting level, using += notation like so:
d['a']+=1
Doing so will return the error:
TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'
To get around this I've built a step that checks whether the key exists before incrementing it, but I'd love to do away with that step if I could.
How should I modify the above autoviv() code to get this enhancement? I've googled and tried different approaches for a few hours but no joy.
Thanks for any advice!
Autovivication is already in Python, inside of
collections'defaultdict.However, if you're trying to implement your own. You should assign your item and then get the reference to it.