Reputation: 13510
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.
Thanks
Upvotes: 1
Views: 359
Reputation: 45542
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:
_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()]
Upvotes: 1
Reputation: 78546
Here's one way to do it using 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}]
Upvotes: 1