You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典键值累加操作出现KeyError错误的原因是什么?

问题原因解析

1. 初始代码无法实现累加的原因

  • Python 字典不允许存在重复键,你在定义word_dict时,重复声明的now、this键会直接覆盖前面的赋值,最终word_dict实际存储内容仅为{'now': 2, 'this': 2},不存在你预期的多个重复键对应的值,自然无法完成累加。
  • 初始代码的赋值逻辑是直接覆盖new_word_dict对应键的值,没有累加逻辑,也会导致最终只能保留最后一次赋值的结果。

2. KeyError报错的触发原因

new_word_dict初始化时是空字典,new_word_dict[word] += n的执行逻辑等价于new_word_dict[word] = new_word_dict[word] + n,第一次遍历到对应键(示例中是now)时,new_word_dict中还不存在该键,读取右值时会直接触发KeyError。

正确实现方案

如果你的原始需求是统计重复键对应的值的总和,首先需要把原始数据修改为不会自动去重的结构(比如元组列表),再做累加处理,示例如下:

# 原始数据改用元组列表存储,避免重复键被覆盖
word_list = [('now', 3), ('this', 3), ('now', 2), ('this', 2)]
new_word_dict = {}

for word, n in word_list:
    # 用get方法设置默认值,键不存在时默认取0
    new_word_dict[word] = new_word_dict.get(word, 0) + n
print(new_word_dict)
# 输出结果:{'now':5, 'this':5}

也可以使用collections.defaultdict简化逻辑:

from collections import defaultdict

word_list = [('now', 3), ('this', 3), ('now', 2), ('this', 2)]
new_word_dict = defaultdict(int)

for word, n in word_list:
    new_word_dict[word] += n
print(dict(new_word_dict))

内容的提问来源于stack exchange,提问作者Jongkeun Choi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 04:06:02