在使用python字典时,避免keyError的最佳方法是什么?

2024-09-24 22:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1

很明显,这将给我一个密钥错误,因为我在使用这个之前没有初始化密钥len(target), len(source)。我知道我可以使用default dict来避免这种错误,但我不确定在这种情况下如何避免它。有没有方法可以防止len(target), len(source)的keyerror和增量值?在


Tags: inselfdefaultsourcetargetforlen错误
3条回答

使用带有默认值param的get(): self.pairLength.get((len(target), len(source)),0)+=1

通常,我推荐setdefault方法;它接受键和默认值作为参数。如果找不到该键,则会为其指定默认值,并返回该值。如果键确实存在,则忽略默认值并进行正常查找:

a = {}
a.setdefault(7, []).append(1)
a
# {7: [1]}
a.setdefault(7, []).append(2)
a
# {7: [1, 2]}

在您的情况下,这不起作用,因为我们没有更改值,而是重新分配它。因此

^{pr2}$

getsetdefault之间的区别在于,get不会在键未命中的情况下分配默认值。它总是保持不变。但既然我们必须明确地重新分配——数字是不可变的——这在这里是合适的。在

使用collections.defaultdictcollections.Counter。这三种方法中的任何一种都可以:

self.pairLength = collections.defaultdict(int)
self.pairLength = collections.defaultdict(lambda: 0)
self.pairLength = collections.Counter()

collections.Counter还有一个额外的优点,即给您self.pairLength.most_common(10),这可能对您的特定应用程序有用。在

如果出于任何原因不能使用新容器,请在执行任何操作之前确保密钥存在:

^{pr2}$

相关问题 更多 >