简体   繁体   中英

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM