我有一个字典列表,如下所示:
[{'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
的情况下做到这一点,我们可以在list
和dict.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}