首页 > 解决方案 > 在 python 循环中修改字典

问题描述

我试图通过将每个事件添加到字典中来计算某些文本中的字母数量,然后在需要时添加它。但是,字典最后显示为空白。我究竟做错了什么?

text = "test 1234!"
dic = {}
for char in text:
    for key, value in dic:
        if key == char:
            value = value + 1
        else:
            dic[char] = 1
print(dic)

谢谢

标签: pythonloopsdictionary

解决方案


无需遍历 dict,您只需检查密钥是否char已存在:

dic = {}
for char in text:
    if char in dic:
        dic[char] += 1
    else:
        dic[char] = 1
print(dic)
# Out: {'t': 2, 'e': 1, 's': 1, ' ': 1, '1': 1, '2': 1, '3': 1, '4': 1, '!': 1}

除了自己编写之外,您还可以使用已实现的模块来执行此类操作。一个选项Counter来自collections模块,它也将返回一个dict

from collections import Counter
counts = Counter(text)
print(counts)
# Out: Counter({'t': 2,
#               'e': 1,
#               's': 1,
#               ' ': 1,
#               '1': 1,
#               '2': 1,
#               '3': 1,
#               '4': 1,
#               '!': 1})

推荐阅读