biggest_boy
biggest_boy

Reputation: 481

Merge duplicate values and sum up total in list of dictionaries

I have a list of dictionaries like so:

[{'asset': 'Discovery Fund', 'amount': 100000, 'rating': 'High'},
 {'asset': 'Ethical Fund', 'amount': 200000, 'rating': 'High'},
 {'asset': 'Foreign Stocks', 'amount': 9350000, 'rating': 'Very High'},
 {'asset': 'Local Stocks', 'amount': 550000, 'rating': 'Very High'}]

I'm trying to merge any duplicate values for the rating key and sum up the amounts. For example, the list above has ratings value as "High", "High", "Very High", "Very High"

Expected result:

[
{'amount': 300000, 'rating': 'High'},
 {'amount': 900000, 'rating': 'Very High'}
]

Please how can I go about this?

Any help would be appreciated.

Thanks

Upvotes: 0

Views: 37

Answers (1)

PacketLoss
PacketLoss

Reputation: 5746

You can achieve this quite easily using pandas.

import pandas as pd

data = [{'asset': 'Discovery Fund', 'amount': 100000, 'rating': 'High'},
 {'asset': 'Ethical Fund', 'amount': 200000, 'rating': 'High'},
 {'asset': 'Foreign Stocks', 'amount': 9350000, 'rating': 'Very High'},
 {'asset': 'Local Stocks', 'amount': 550000, 'rating': 'Very High'}]

df = pd.DataFrame(data)

output = df.groupby('rating', as_index=False).sum().to_dict('records')

print(output)
#[{'rating': 'High', 'amount': 300000}, {'rating': 'Very High', 'amount': 9900000}]

To do this without pandas we can use a loop over our list and dict.get() to grab the value, or 0 for key rating.

output = {}

for _dict in data:
    output[_dict['rating']] = output.get(_dict['rating'], 0) + _dict['amount']

output
#{'High': 300000, 'Very High': 9900000}

Upvotes: 1

Related Questions