python - 如何添加键值而不是替换它们。 Python 字典

标签 python dictionary

1st Text file format . 
cake,60
cake,30
tart,50
bread,89  

2nd Text file format . 
cake,10
cake,10
tart,10
bread,10  

我尝试过的代码。

from collections import defaultdict
answer = defaultdict(int)
recordNum = int(input("Which txt files do you want to read from "))
count = 1
counter = 0
counst = 1
countesr = 0
while recordNum > counter:
  with open('txt'+str(count)+'.txt', 'r') as f:
      for line in f:
          k, v = line.strip().split(',')
          answer[k.strip()] += int(v.strip())
          count = count+1
          counter = counter+1
print(answer)

问题。

I want the dictionary to be {'cake': '100', 'tart': '60', 'bread': '99'}

but it prints like this  {'cake': '30', 'tart': '50', 'bread': '89'}

“蛋糕”值不是与 txt 文件一和二中的其他蛋糕值相加,而是被替换为最新值。我该如何解决这个问题。

最佳答案

您可以使用collections.defaultdict累积计数:

from collections import defaultdict

answer = defaultdict(int)
with open("file.txt", 'r') as f:
    for line in f:
        k, v = line.split(',')
        answer[k.strip()] += int(v.strip())

# turn values back to string
for k in answer:
    answer[k] = str(answer[k])
print(answer)

如果计数均为正数,您可以考虑使用collections.Counter

关于python - 如何添加键值而不是替换它们。 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45797365/

相关文章:

python - 具有增强图像和其他功能的 Keras 迭代器

来自 mobypos.txt 文件的 Python 字典

python - 创建以文件名作为键的目录字典

python - Ubuntu 16.04/Django - gunicorn - Worker 启动失败

javascript - 不要使用 for 循环交替推送到数组

Python - 创建循环遍历嵌套列表的字典列表

具有列表值的python字典 - 使用列表更新一个键会更新具有相同列表的所有键

python - 在没有循环的情况下更改列表中的值

python - 'from .. import module' 是什么意思?

python - Seaborn 直方图使列变白