Federico De Marco
Federico De Marco

Reputation: 341

Django, how to sum queryset value in dictionary values

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

Answers (1)

Flux
Flux

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())]:

  1. [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])]
  2. [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)]]
  3. [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))]
  4. [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Upvotes: 3

Related Questions