tree em
tree em

Reputation: 21701

group few lists of dictionary by key

lst1 = [
   {"id": "A", "a": "one"}, 
   {"id": "B", "b": "two"}
]
lst2 = [
   {"id": "A", "a1": "Three"},
   {"id": "B", "b1": "Four"},  
   {"id": "C", "c1": "Four"}
 ]
lst3 = [
  {"id": "A", "c1": "Five"},
  {"id": "B", "d1": "Six"}
]

a = lst1+lst2+lst3

res = [
     {'id': 'A', 'a': 'one'},
     {'id': 'B', 'b': 'two'},
     {'id': 'A', 'a1': 'Three'},
     {'id': 'B', 'b1': 'Four'},
     {'id': 'C', 'c1': 'Four'},
     {'id': 'A', 'c1': 'Five'}, 
     {'id': 'B', 'd1': 'Six'}
 ]

I want to group by Id the res will look like this

res = [
     {'id': 'A', 'a': 'one','a1': 'Three','c1': 'Five'},
     {'id': 'B', 'b': 'two', 'b1': 'Four', 'd1': 'Six'},
     {'id': 'C', 'c1': 'Four'},
 ]

What I have tried:

result = []
for l1, l2,l3 in zip(lst1, lst2,lst3):
    result.append({**l1 , **l2 , **l3})

print(result)

Upvotes: 0

Views: 38

Answers (2)

John Lehmann
John Lehmann

Reputation: 1036

def coalesce(updates: list[dict[str,str]], join_key):
   res = {}
   for upd in updates:
      for rec in upd:
         key = rec[join_key]
         if not key in res:
            res[key] = {join_key: key}
         res[key].update(rec)
   return res.values()


recs = [lst1, lst2, lst3]
for value in coalesce(recs, "id"):
   print(value)

Upvotes: 0

Ben Grossmann
Ben Grossmann

Reputation: 4772

Here's one approach:

arr = [
     {'id': 'A', 'a': 'one'},
     {'id': 'B', 'b': 'two'},
     {'id': 'A', 'a1': 'Three'},
     {'id': 'B', 'b1': 'Four'},
     {'id': 'C', 'c1': 'Four'},
     {'id': 'A', 'c1': 'Five'}, 
     {'id': 'B', 'd1': 'Six'}
 ]

res_dict = {d['id']:{'id':d['id']} for d in arr}
for d in arr:
    res_dict[d['id']].update(d)
res = list(res_dict.values())

The resulting list res:

[{'id': 'A', 'a': 'one', 'a1': 'Three', 'c1': 'Five'},
 {'id': 'B', 'b': 'two', 'b1': 'Four', 'd1': 'Six'},
 {'id': 'C', 'c1': 'Four'}]

Upvotes: 2

Related Questions