Reputation: 341
I have the following queryset dictionary:
{'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
In which I have as Key the category of my products and as items 12 values, that represent the sum of each month. I want to calculate the cross sum of all keys of each items, as the following example:
{'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
How could I obtain it?
Upvotes: 0
Views: 387
Reputation: 10920
You can use zip
, sum
, and list comprehension:
d = {
'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
}
sum_dict = {
'Total': [sum(t) for t in zip(*d.values())],
}
# sum_dict = {'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
Step-by-step explanation of [sum(t) for t in zip(*d.values())]
:
[sum(t) for t in zip([100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])]
[sum(t) for t in [(100.0, 103.0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]]
[sum((100.0, 103.0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0))]
[203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Upvotes: 3