将列表转换为字典并添加重复的键值

时间:2019-03-26 00:56:25

标签: python list dictionary

我试图找到这样的dict值

{'deepak': 0, 'nayak': 0}

我以此方式尝试过

d={}
d['deepak'] = 0
d['nayak'] = 0 
f = [ '1, deepak, 15',
'2, nayak, 10',
 '3, deepak, 10',
 '4, nayak, 13']
for lines in f:
print(lines)
##appropriate logic to excute#
    print(d)

预期o / p应该是

{'deepak': 25, 'nayak': 23}

3 个答案:

答案 0 :(得分:2)

你差不多在那里

d = {}

f = [ '1, deepak, 15',
'2, nayak, 10',
 '3, deepak, 10',
 '4, nayak, 13']

for line in f:
    # by splitting on the comma and trailing space
    # you can unpack those three entries into a throw-away var,
    # k, and v and you only need to convert v to int
    _, k, v = line.split(', ')
    d[k] = d.get(k, 0) + int(v)

d
{'deepak': 25, 'nayak': 23}


答案 1 :(得分:1)

您可以使用Counter模块中的collections来减少使用常规词典时所需的样板

from collections import Counter

f = [
    '1, deepak, 15',
    '2, nayak, 10',
    '3, deepak, 10',
    '4, nayak, 13'
]

result = Counter()

for x in f:
    _, name, count = x.split(', ')
    result[name] += int(count)

print(result)

答案 2 :(得分:0)

d={}
d['deepak'] = 0
d['nayak'] = 0 
f = [ '1, deepak, 15',
'2, nayak, 10',
 '3, deepak, 10',
 '4, nayak, 13']
for lines in f:
    print(lines)
    ##appropriate logic to excute#
    line = lines.split(', ')
    d[line[1]] += int(line[-1])
print(d)