gpt4 book ai didi

python - 如何在 python 字典列表中组合值

转载 作者:太空宇宙 更新时间:2023-11-04 07:39:34 24 4
gpt4 key购买 nike

我有一个看起来像这样的字典列表:

l = [{'name': 'john', 'amount': 50}, {'name': 'al', 'amount': 20}, {'name': 'john', 'amount': 80}]

有什么方法可以合并/合并匹配的名称值字典并求和吗?

最佳答案

您可以使用 collections.Counter() object将名称映射到数量,并在进行时对它们求和:

from collections import Counter

summed = Counter()
for d in l:
summed[d['name']] += d['amount']
result = [{'name': name, 'amount': amount} for name, amount in summed.most_common()]

然后结果也按金额排序(最高在前):

>>> from collections import Counter
>>> l = [{'name': 'john', 'amount': 50}, {'name': 'al', 'amount': 20}, {'name': 'john', 'amount': 80}]
>>> summed = Counter()
>>> for d in l:
... summed[d['name']] += d['amount']
...
>>> summed
Counter({'john': 130, 'al': 20})
>>> [{'name': name, 'amount': amount} for name, amount in summed.most_common()]
[{'amount': 130, 'name': 'john'}, {'amount': 20, 'name': 'al'}]

关于python - 如何在 python 字典列表中组合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25285744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com