Python字典中If条件的KeyError



我有这个问题:

我有这样一段代码,它试图在一个文本文件中计算双元组。if语句检查元组是否在字典中。如果是,则值(计数器(增加一。如果它不存在,代码应该创建一个以元组为键、值为1的键值对。

for i in range(len(temp_list)-1):
temp_tuple=(temp_list[i], temp_list[i+1])
if bigramdict[temp_tuple] in bigramdict:
bigramdict[temp_tuple] = bigramdict[temp_tuple]+1
else:
bigramdict[temp_tuple] = 1

然而,每当我运行代码时,它都会在第一个元组上抛出一个KeyError。据我所知,当dict中的键不存在时,就会抛出KeyError,这里就是这种情况。这就是为什么我有if语句来查看是否有密钥。通常,程序应该看到没有键,然后转到其他键来创建一个键。

然而,它在if上卡住了,并抱怨缺少钥匙。

为什么它不承认这是一个条件语句?

请帮忙。

你想做的是

if temp_tuple in bigramdict:

而不是

if bigramdict[temp_tuple] in bigramdict:

对于更Python的解决方案,您可以通过将temp_list中的相邻项与自身压缩但偏移量为1来对其进行配对,并使用dict.get方法将丢失键的值默认为0:

for temp_tuple in zip(temp_list, temp_list[1:]):
bigramdict[temp_tuple] = bigramdict.get(temp_tuple, 0) + 1

最新更新