使用Python字典求和值

时间:2013-09-07 08:39:11

标签: python dictionary

我想知道如何使用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)

3 个答案:

答案 0 :(得分:4)

使用collections.Counter() object

from collections import Counter

my_dict = Counter()

with open('test.txt') as f:
    for line in f:
        word, freq = line.split()
        my_dict[word] += int(freq)

请注意,不需要str.rstrip(),不带参数的str.split()调用剥离字符串。

除了将不存在的密钥默认为0之外,Counter()个对象还有其他优点,例如列出按频率排序的单词(包括前N个),求和和减去。

上面的代码导致:

>>> my_dict
Counter({'word1': 7, 'word2': 4, 'word3': 1})
>>> for word, freq in my_dict.most_common():
...     print word, freq
... 
word1 7
word2 4
word3 1

答案 1 :(得分:2)

您可以使用defaultdict

import collections
d = collections.defaultdict(int)
with open('text.txt') as f:
    for row in f:
        temp = row.split()
        d[temp[0]] += int(temp[1])

d现在是:

defaultdict(<type 'int'>, {'word1': 7, 'word3': 1, 'word2': 4})

答案 2 :(得分:0)

如果有人正在处理多个列(在我的情况下,我遇到了同样的问题,但有4列):

这应该可以解决问题:

from collections import defaultdict

my_dict = defaultdict(int)

with open("input") as f:
    for line in f:
        if line.strip():
            items = line.split()
            freq = items[-1]
            lemma = tuple(items[:-1]) 

            my_dict[lemma] += int(freq)

for items, freq in my_dict.items():
    print items, freq