字典 Python 中 If-Condition 上的 KeyError

PyD*_*Dev 5 python dictionary if-statement tuples python-3.x

我有这个问题:

我有这段代码试图计算文本文件中的二元数。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
Run Code Online (Sandbox Code Playgroud)

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

但是,它卡在 if 上并抱怨缺少密钥。

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

请帮忙。

Cap*_*jan 7

你试图做的是

if temp_tuple in bigramdict:
Run Code Online (Sandbox Code Playgroud)

代替

if bigramdict[temp_tuple] in bigramdict:
Run Code Online (Sandbox Code Playgroud)