字典Python

问题描述

我有这个问题:

我有这段代码正在尝试计算文本文件中的双字母组。 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语句来查看是否有键的原因。通常,程序应该看到没有密钥,然后转到else来创建密钥。

但是,它卡在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