简体   繁体   中英

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.

Thanks

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}]
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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM