我想知道如何使用 Python 字典对值求和。我逐行读取巨大的文件并为每个特定键增加值。假设我有以下玩具文件:
word1 5
word2 3
word3 1
word1 2
word2 1
我期望的结果是:
my_dict = {'word1':7, 'word2':4, 'word3':1}
下面粘贴的是我目前的工作。
my_dict = {}
with open('test.txt') as f:
for line in f:
line = line.rstrip()
line = line.split()
word = line[0]
frequency = line[1]
my_dict[word] += int(frequency)