gpt4 book ai didi

python - 按特定键将两个字典列表合并为一个字典列表

转载 作者:行者123 更新时间:2023-12-01 05:02:45 25 4
gpt4 key购买 nike

我正在努力实现以下目标:

给定

a = [{'val': 10, 'count': 1}]
b = [{'val': 10, 'count': 4}, {'val': 20, 'count': 2}]

我想得到

output = [{'val': 10, 'count': 5}, {'val': 20, 'count': 2}]

也就是说,根据 val 合并 2 个字典列表:如果 2 个字典实例中的 val 相同,则通过对计数求和来合并,否则保留 2 个实例。

顺便说一句,性能是一个问题,因此首选优雅且快速的解决方案。

谢谢!

最佳答案

基于@Brionius的想法,您可以使用Counter来操作数据和 List comprehension :

我们将获取数据并创建一个可以通过 Counter 轻松使用的字典,然后我们可以将数据相加,最后恢复到我们想要的格式(您的原始格式)。

from collections import Counter

a = [{'val': 10, 'count': 1}]
b = [{'val': 10, 'count': 4}, {'val': 20, 'count': 2}]
c = Counter()

[c.update({d['val']:d['count']}) for d in a + b]
print [{'val': k, 'count': v} for k, v in c.iteritems()]

输出:

[{'count': 5, 'val': 10}, {'count': 2, 'val': 20}]

关于python - 按特定键将两个字典列表合并为一个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711147/

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