Home > Software engineering >  Combine lists of dictionaries with specific value matches
Combine lists of dictionaries with specific value matches

Time:05-15

Given a_list and b_list in python, I want to merge them so that the result is c_list.

In the example below, only want to merge elements that have a matching 'A' for the 'code' key.

a_list = [{'code': 'A', 'foo_sum': 1}, {'code': 'B', 'foo_sum': 2}]
b_list = [{'code': 'A', 'bar_sum': 3}]

c_list = [{'code': 'A', 'foo_sum': 1, 'bar_sum': 3}, {'code': 'B', 'foo_sum': 2}]

I wanted to use numpy, but could not use it because it did not necessarily match the element length and the order.

And, I tried to determine this in the iterative process, but could not achieve to make it c because local variables are not available in the comprehension notation.

for a in b_list:
    if any(b["code"] == a["code"] for i, b in enumerate(b_list):
        # want to use i variable, but not dified.
        a["bar_sum"] = b_list[i]["code"]

CodePudding user response:

You can try

  1. merge the two lists
  2. sort the merged list by code key then groupby code
  3. merge the list of dictionary in group to one dictionary
from itertools import groupby
from collections import ChainMap

c_list = a_list   b_list
c_list = sorted(c_list, key=lambda d: d.get('code'))
res = [dict(ChainMap(*group)) for key, group in groupby(c_list, lambda d: d.get('code'))]
print(res)

[{'code': 'A', 'bar_sum': 3, 'foo_sum': 1}, {'code': 'B', 'foo_sum': 2}]

CodePudding user response:

Another solution:

a_list = [{"code": "A", "foo_sum": 1}, {"code": "B", "foo_sum": 2}]
b_list = [{"code": "A", "bar_sum": 3}]


out = {}
for d in a_list   b_list:
    out[d["code"]] = {**out.get(d["code"], {}), **d}

print(list(out.values()))

Prints:

[{"code": "A", "foo_sum": 1, "bar_sum": 3}, {"code": "B", "foo_sum": 2}]
  • Related