当我将+ =放入字典而不是=时出现错误的原因

时间:2018-07-12 02:32:45

标签: python dictionary

当我在Python(3.6)代码下运行时,出现错误(请参阅#KeyError注释行)。但是,当我将dictionary [res] + = 1更改为dictionary [res] = 1时,它运行良好。考虑到该dict通常允许运算符'+ =',所以不知道为什么这次不这样做。有人知道原因吗?

words = ["gin", "zen", "gig", "msg"]
Morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
dictionary = {}

for _ in words:
    tmp = []
    for c in _:
        tmp.append(Morse[ord(c) - ord('a')])  # take the code
    res = ''.join(tmp)
    dictionary[res] += 1  # KeyError
cnt = 0
for i in enumerate(dictionary):
    cnt += 1

错误消息为:

Traceback (most recent call last):
    File "<input>", line 10, in <module>
KeyError: '--...-.'

2 个答案:

答案 0 :(得分:1)

在您的for循环内,字典继续为空,因此它没有键[res]

还有一件事,您不建议使用underscore作为变量名。

答案 1 :(得分:1)

+==之间的区别在于,前者假定那里已经存在某些东西,而=是一个赋值,如果该条目不存在,则创建该条目。您的dict没有任何条目,因此+=是无效的操作。

您可以使用Counter,它实际上是dict,其中的值为ints,默认值为0。

from collections import Counter

words = ["gin", "zen", "gig", "msg"]
Morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
dictionary = Counter()

for w in words:
    tmp = []
    for c in w:
        tmp.append(Morse[ord(c) - ord('a')])  # take the code
    res = ''.join(tmp)
    dictionary[res] += 1

print(dictionary)