Reputation: 83
very new to python and hope can get some help here. I'm trying to sum up the total from different lists in dictionary
{'1': [0, 2, 2, 0, 0], '2': [0, 1, 1, 0, 0], '3': [2, 4, 2, 0, 2]}
I have been trying to find a way to sum up the total as follow and append in a new list:
'1': [0, 2, 2, 0, 0]
'2': [0, 1, 1, 0, 0]
'3': [2, 4, 2, 0, 2]
0+0+2 = 2
2+1+4 = 7
2+1+2 = 5
[2, 7, 5, 0, 2]
I was able to get partial results for one row if I do this way but wasn't able ti figure out a way to get the output I want.
total_all = list()
for x, result_total in result_all.items():
new_total = (result_total[1])
total_all.append((new_total))
print(sum(total_all))
output 7
Any suggestions and help would be greatly appreciated
Upvotes: 0
Views: 171
Reputation: 195408
Using zip()
(doc) function to transpose dictionary values and sum()
to sum them inside list comprehension:
d = {'1': [0, 2, 2, 0, 0], '2': [0, 1, 1, 0, 0], '3': [2, 4, 2, 0, 2]}
out = [sum(i) for i in zip(*d.values())]
print(out)
Prints:
[2, 7, 5, 0, 2]
EDIT (little explanation):
The star-expression *
inside zip()
effectively unpacks dict values into this:
out = [sum(i) for i in zip([0, 2, 2, 0, 0], [0, 1, 1, 0, 0], [2, 4, 2, 0, 2])]
zip()
iterates over each of it's argument:
1. iteration -> (0, 0, 2)
2. iteration -> (2, 1, 4)
...
sum()
does sum of these tuples:
1. iteration -> sum( (0, 0, 2) ) -> 2
2. iteration -> sum( (2, 1, 4) ) -> 7
...
Upvotes: 2
Reputation: 16081
You can do like this,
In [6]: list(map(sum,zip(*d.values())))
Out[6]: [2, 7, 5, 0, 2]
Upvotes: 0