我正在尝试对字符串进行计数,我想删除值为 1 和 2 的键。我可以使用以下脚本成功地对字符串进行计数。如果我将 if 循环添加到字典中,当我尝试打印它时它会抛出 Key error 'd'。
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1:
del freq[w]
print (w, freq[w])
check_freq(s)
错误如下
File "<ipython-input-60-a79c71ac1b31>", line 10, in check_freq
print (w, freq[w])
KeyError: 'd'
预期输出
{'a': 3, 'b': 3}
最佳答案
如果删除 key ,如何打印?因为 key 已删除,所以它会引发 KeyError,因为 key 不再存在。删除的时候加个continue就可以了。
s = "aaabbbd"
def check_freq(s):
freq = {}
for c in s:
freq[c] = s.count(c)
for w in sorted(freq, key=freq.get, reverse=True):
if freq[w] == 1:
del freq[w]
continue
print (w, freq[w])
return freq
result = check_freq(s)
>a 3
b 3
result
> {'a': 3, 'b': 3}
关于python - 删除键时字典中的键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930079/