这个 KeyError 是什么意思?在 python 中字典的累积键值

What does this KeyError mean? in Accumulation key value of dictionary in python

(1) :这确实有效,但不会累积。

word_dict = {'now': 3, 'this': 3, 'now': 2, 'this': 2}
new_word_dict = {}

for word in word_dict:
    n = word_dict.get(word)

    new_word_dict[word] = n
    print(new_word_dict)

(1) 结果

    {'now': 2}
    {'now': 2, 'this': 2}

(2) :这不起作用。 KeyError 是什么?

word_dict = {'now': 3, 'this': 3, 'now': 2, 'this': 2}
new_word_dict = {}

for word in word_dict:
    n = word_dict.get(word)

    new_word_dict[word] += n
    print(new_word_dict)

(2) 结果

  ---->  new_word_dict[word] += n
  
 KeyError: 'now'

new_word_dict[word] += n 需要 new_word_dict[word] 的最新值,如果它没有初始化,它应该会崩溃。

要解决此问题,您可以检查 new_word_dict 是否存在,例如 new_word_dict[word] = n if new_word_dict[word] else new_word_dict[word] + n

你也可以像for key, value in word_dict.items()

一样使用word_dict.items()

KeyError 是因为您尝试增加的密钥不存在,但我认为您的示例中不仅仅存在这个问题。

假设您想要的结果是 new_word_dictword_dict 的累加,您首先需要将 word_dict 的类型更改为元组列表(因为,作为@ deceze 在评论中指出,字典中不允许使用重复键)。所以我想你想以这样的方式结束:

words == [("now", 3), ("this", 3), ("now", 2), ("this", 2)]
words_accumulated == {"now": 5, "this": 5}

那么你的循环可以改为

words = [("now", 3), ("this", 3), ("now", 2), ("this", 2)]
words_accumulated = {}
for word, val in words: # unpack each tuple into two variables
  existing_val = words_accumulated.setdefault(word, 0) # if it doesn't exist yet, set to 0. This solves your KeyError
  words_accumulated[word] = existing_val + val

要进一步研究如何更好地做到这一点,请查找 defaultdict and maybe some of the tools in itertools