Joan Triay Joan Triay - 19 days ago 5
Python Question

Sum different elements of a list of lists using one dictionary (Python)

I have this list of lists:

[Racing, 100]
[Crossi, 100]
[Racing, 120]
[Racing, 130]
[Marcas, 105]
[Marcas, 109]
[Crossi, 130]
[Crossi, 104]


I want the total Sum for Racing, Marcas and Crossi. I want do it with a dictonary on python if it's possible. Like this:

Brads{"Crossi": 334, "Marcas": 214, "Racing":350}


Is it possible do it with only one "for bucle"?

Answer
from collections import defaultdict
list_ = [['Racing', 100],['Crossi', 100],['Racing', 120],['Racing', 130],['Marcas', 105],['Marcas', 109],['Crossi', 130],['Crossi', 104]]
dic = defaultdict(int)
for i in list_:
    dic[i[0]] += i[1]
print(dic)

out:

defaultdict(<class 'int'>, {'Marcas': 214, 'Crossi': 334, 'Racing': 350})

setdefault:

list_ = [['Racing', 100],['Crossi', 100],['Racing', 120],['Racing', 130],['Marcas', 105],['Marcas', 109],['Crossi', 130],['Crossi', 104]]
d = {}
for k,v in list_:
    d[k] = d.setdefault(k,0) + v
print(d)

out:

{'Marcas': 214, 'Crossi': 334, 'Racing': 350}