python字典中的求和

Vig*_*raj 2 python python-2.7 python-3.x

如何使用for循环在python中创建字典

CPO     1
CL      1
SL      1
EL      1
CPO     1
SL      1
CPO     1
Run Code Online (Sandbox Code Playgroud)

所以预期结果应该如下{'CPO':3,'CL':1,'SL':2,'EL':1}

我试过这个:

avail = defaultdict(list)
    cpo = cl = sl= el = 0
    for i in hr_line_id:
        if i.leave_code == 'CPO':
            cpo = cpo + i.no_of_days
            avail['cpo'].append(cpo)
        elif i.leave_code == 'CL':
            cl = cl + i.no_of_days
            avail['cl'].append(cl)
        elif i.leave_code == 'SL':
            sl = sl + i.no_of_days
            avail['sl'].append(sl)
    print avail
Run Code Online (Sandbox Code Playgroud)

Eri*_*nil 5

正如@JeanFrancoisFabre所提到的,这是一个完美的例子collections.Counter:

from collections import Counter

text = """CPO     1
CL      1
SL      1
EL      1
CPO     1
SL      1
CPO     1"""

count = Counter()

for line in text.split("\n"):
    k,v = line.split()
    count[k] += int(v)

print(count)
Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})
Run Code Online (Sandbox Code Playgroud)

如果您需要小写键,可以使用count[k.lower()] += int(v):

Counter({'cpo': 3, 'sl': 2, 'cl': 1, 'el': 1})
Run Code Online (Sandbox Code Playgroud)

如果总是数量1,你可以简单地写一个单行:

Counter(line.split()[0] for line in text.split("\n"))
# Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})
Run Code Online (Sandbox Code Playgroud)