python - 删除键时字典中的键错误

标签 python dictionary

我正在尝试对字符串进行计数,我想删除值为 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/

相关文章:

javascript - 从 python/Flask 应用程序写入 HTML5 localStorage

python 内存问题

python - 将两个用户定义函数中的 ax 和 fig 合并到一个图中?

python - 在 python 中创建类似于 MS 计算器的 GUI 计算器

python - 在类的 __iter__ 方法中生成字典键、值对

python - 更新字典中多个键值对的性能

具有稀疏序列的Python数据结构

Swift MapKit 多边形叠加

c# - 如何使用 uint 作为键在字典中存储函数 (C#)

python - 自创建模块用于异步导入