合并重复值并在字典列表中求和



我有一个字典列表,如下所示:

[{'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'}]

我正在尝试合并评级键的任何重复值并汇总金额。例如,上面的列表的评级值为"High", "Very High", "Very High">

预期结果:

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

请问我该怎么做?

如有任何帮助,不胜感激。

感谢

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

要在没有pandas的情况下做到这一点,我们可以在listdict.get()上使用loop来获取值,或者为rating键使用0。

output = {}
for _dict in data:
output[_dict['rating']] = output.get(_dict['rating'], 0) + _dict['amount']
output
#{'High': 300000, 'Very High': 9900000}

最新更新