Sum values of duplicate(common) keys in a list of dictionary

Viewed 147

I am trying to get the sum of duplicated key values in list

tax = [{'taxType': 'T1', 'amount': 140},{'taxType': 'T1', 'amount': 10}]

Expected result

tax = [{'taxType': 'T1', 'amount': 150}]

If T1 is the same key and 150 is the result of sum amount values

1 Answers

Following up on @python_user's comment

Here is how you implement the solution for your code

tax = [{'taxType': 'T1', 'amount': 140},{'taxType': 'T1', 'amount': 10}]

aggregated_data = {}

for dictionary in tax:
    key = (dictionary['taxType'])
   
    aggregated_data[key] = aggregated_data.get(key, 0) + dictionary['amount']
    
tax = [{'taxType': key, 'amount': value} for key, value in aggregated_data.items()]

print(tax)

output

[{'taxType': 'T1', 'amount': 150}]
Related