[英]How to sum values in dicts if some key in that dicts has same month?
I have Django queryset: 我有Django queryset:
summary = Contracts.objects.all() \
.filter(datestart__gte=time_threshold) \
.values('datestart', 'id_deposits__id_valuta__name') \
.annotate(sum=Sum('suma')) \
.order_by('-id_deposits__id_valuta__name')
And I catch qs by: 我通过以下方式捕捉到qs:
for s in summary:
for k, v in CURRENCY.items():
if s['id_deposits__id_valuta__name'] == k:
s['sum'] *= CURRENCY[k]
It updates currency sum, as needed. 它会根据需要更新货币金额。 It returns dicts 它返回字典
{'sum': Decimal('400000.00'), 'datestart': datetime.date(2016, 3, 1), 'id_deposits__id_valuta__name': 'Гривня'}
{'sum': Decimal('2500000.00'), 'datestart': datetime.date(2016, 4, 25), 'id_deposits__id_valuta__name': 'Долар'}
{'sum': Decimal('2500000.00'), 'datestart': datetime.date(2016, 4, 25), 'id_deposits__id_valuta__name': 'Долар'}
Now i need to sum that value of "sum" key in dicts, when months in "datestart" value are equal. 现在,当“ datestart”值中的月份相等时,我需要对字典中“ sum”键的值求和。
Ex. 防爆。 some dicts has sum, datestart keys. 有些字典有sum,datestart键。 I need to have sum of 'sum' values when dicts has same month: 2016-04-03, 2016-04-14 当字典在同一个月时,我需要具有“和”值的总和:2016-04-03,2016-04-14
So how to do this in minimalistic way? 那么如何以简约的方式做到这一点呢?
You can convert every dictionary to Counter
where month is key and value is s['sum']
and then add them together: 您可以将每个字典转换为以月为键且值为s['sum']
Counter
,然后将它们加在一起:
from collections import Counter
sum((Counter({x['datestart'].month: x['sum']}) for x in summary), Counter())
# Counter({4: Decimal('5000000.00'), 3: Decimal('400000.00')})
Note that if you need to differentiate the month and year use {(x['datestart'].month, x['datestart'].year): x['sum']}
instead. 请注意,如果需要区分月份和年份,请改用{(x['datestart'].month, x['datestart'].year): x['sum']}
。
Use a dictionary to track the sum per month; 使用字典来跟踪每月的总和; you could use a defaultdict
here to manage initial values: 您可以在此处使用defaultdict
来管理初始值:
from collections import defaultdict
from decimal import Decimal
per_month = defaultdict(Decimal)
for s in summary:
s['sum'] *= CURRENCY.get(s['id_deposits__id_valuta__name'], 1)
month = s['datestart'].year, s['datestart'].month
per_month[month] += s['sum']
I've removed your loop over CURRENCY.items()
; 我已经通过CURRENCY.items()
删除了您的循环; you can just use dict.get()
to get the value instead; 您可以只使用dict.get()
来获取值; if the key isn't in the dictionary, 1
is used instead. 如果键不在词典中,则使用1
代替。
Note that I am grouping your sums on (year, month)
tuples, assuming that you want months in different years to be treated as separate sums. 请注意,假设您希望将不同年份中的月份作为单独的总和,我将您的总和分组为(year, month)
元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.