[英]Python - merge two list of dictionaries adding values of repeated keys
So I have two list of dictionaries which look like the following: 因此,我有两个字典列表,如下所示:
A = [{'id':'xyz', 'count': 3},{'id':'zzz', 'count': 1}]
B = [{'id':'xyz', 'count': 4}]
I want the final output to be like: 我希望最终输出像:
C = [{'id':'xyz', 'count': 7},{'id':'zzz', 'count': 1}]
So in case that if the value of the first key is the same in both lists, we add up the values for the second key. 因此,如果两个列表中第一个键的值相同,我们将第二个键的值相加。 Any idea how I might achieve this? 知道如何实现吗? So far I have tried: 到目前为止,我已经尝试过:
for elem in A:
if elem['id'] in B.elementsKey['id']:
# TO DO
I am stock where I am trying to update the value for the other element accordingly. 我在库存中尝试相应地更新其他元素的值。
NOTE: Each id is unique. 注意:每个ID是唯一的。
Thanks 谢谢
Here's one way to do it using itertools.groupby
: 这是使用itertools.groupby
的一种方法:
from itertools import groupby
from operator import itemgetter
f = itemgetter('id')
lst = [{'id': k, 'count': sum(d['count'] for d in g)}
for k, g in groupby(sorted(A+B, key=f), f)]
print(lst)
# [{'id': 'xyz', 'count': 7}, {'id': 'zzz', 'count': 1}]
from collections import Counter
C_counts = Counter()
for l in (A, B):
C_counts.update({x['id']: x['count'] for x in l})
C = [{'id':k, 'count':c} for (k, c) in C_counts.items()]
If you really don't want to import collections.Counter
you can do: 如果您确实不想导入collections.Counter
,可以执行以下操作:
_C = {}
for l in A, B:
for d in l:
_C[d['id']] = d['count'] + _C.get(d['id'], 0)
C = [{'id':k, 'count':c} for (k, c) in _C.items()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.