我正在使用一些常见的 python autovivification 代码构建字典:
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
我希望能够做的一件事是在指定的字典嵌套级别当前不存在键的情况下增加值,使用 += 表示法,如下所示:
d['a']+=1
这样做会返回错误:
TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'
为了解决这个问题,我构建了一个步骤,在增加密钥之前检查密钥是否存在,但如果可以的话,我很乐意取消该步骤。
我应该如何修改上面的 autoviv() 代码来获得这种增强?我已经用谷歌搜索并尝试了几个小时的不同方法,但没有任何乐趣。
感谢您的任何建议!