I have two list of dict:
list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]
how can I create a new list of dict with the same keys and add the values of the “amount” of each dict that has the same “month”?
target = [{"month": "Jan", "amount":3}, {"month": "Feb", "amount": 8}]
3
How about this:
list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]
count = dict()
for lst in list1 + list2:
m = lst.get('month')
if m not in count:
count[m] = 0
count[m] += int(lst.get('amount', 0))
target = [{'month': m, 'amount': c} for m, c in count.items()]
This implements what I auggested above:
from collections import defaultdict
list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]
months = defaultdict(int)
for l in (list1,list2):
for d in l:
months[d['month']] += d['amount']
print(months)
target = [{'month':k,'amount':v} for k,v in months.items()]
print(target)
Output:
defaultdict(<class 'int'>, {'Jan': 3, 'Feb': 8})
[{'month': 'Jan', 'amount': 3}, {'month': 'Feb', 'amount': 8}]
I used a defaultdict for simplicity, but a normal dictionary would also work with the usual if d['month'] not in months:
protection.
1