0

我正在使用一些常见的 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() 代码来获得这种增强?我已经用谷歌搜索并尝试了几个小时的不同方法,但没有任何乐趣。

感谢您的任何建议!

4

1 回答 1

0

Autovivication 已经在 Python 中,位于collections'defaultdict中。

from collections import defaultdict


#Let's say we want to count every character
#  that occurs
text = "Let's implement autovivication!"
di = defaultdict(int)
for char in text:
    di[char] += 1
print(di)

#Another way of doing this is using a defualt string
#  (or default int, or whatever you want)
currentDict = {'bob':'password','mike':'12345'}
di = defaultdict(lambda:'unknown user', currentDict)
print(di['bob'])
print(di['sheryl'])

但是,如果您尝试实现自己的。您应该分配您的项目,然后获取对它的引用。

def __getitem__(self, item):  
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()        
        return dict.__getitem__(self, item)
于 2017-11-14T22:44:18.520 回答