【问题标题】:KeyError on If-Condition in dictionary Python字典Python中If-Condition的KeyError
【发布时间】:2021-01-06 23:19:13
【问题描述】:

我有这个问题:

我有这段代码试图计算文本文件中的二元组。 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 语句来查看是否有密钥。正常情况下,程序应该看到没有key,然后去else创建一个。

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

为什么它不识别这是一个条件语句?

请帮忙。

【问题讨论】:

  • 这能回答你的问题吗? I'm getting Key error in python
  • bigramdict = Counter(zip(temp_list, temp_list[1:]))。 (这不是最有效的方法,而是最短且最容易理解的方法。)

标签: python python-3.x dictionary if-statement tuples


【解决方案1】:

你想要做的是

if temp_tuple in bigramdict:

而不是

if bigramdict[temp_tuple] in bigramdict:

【讨论】:

  • 天啊,非常感谢,你说得对!我有一个类似的功能,我使用了一个迭代器,我把它复制了一遍,没有意识到我的错误。非常感谢您的快速回答!
  • @PyDev Gotcha ;)
【解决方案2】:

对于更 Pythonic 的解决方案,您可以将 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

【讨论】:

  • 代替默认的get,你也可以使用defaultdict; from collections import defaultdict // bigramdict = defaultdict(int) // bigramdict[temp_tuple] += 1.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多