pythonlistdictionary

How to create a new list of dicts based on 2 lists with added value of both lists of dicts that have the same key


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}]

Solution

  • 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.