'Concat 2 list of dictionaries with same id

I have 2 lists of dictionaries

a = [{'id':1, 'name':'John Doe'}, {'id':2, 'name':'Jane Doe'}, {'id':4, 'name':'Sample Doe'}]
b = [{'id':1, 'rating':9}, {'id':2, 'rating':7}, {'id':3, 'rating':8}]

Is there a way to concat b to a if the id b is on id a?

[{'id':1, 'name':'John Doe', 'rating':9}, {'id':2, 'name':'Jane Doe', 'rating':7}, {'id':4, 'name':'Sample Doe', 'rating':0}]


Solution 1:[1]

This should work:

[{**item1, **item2} for item1 in a for item2 in b if item1['id'] == item2['id']]

It iterates over the the two dict so it is O(n^2), but it is clear and concise. {**item1, **item2} means adds the key value pairs from item1, then the key value pairs from item2. Here, the results will be:

[{'id': 1, 'name': 'John Doe', 'rating': 9},
 {'id': 2, 'name': 'Jane Doe', 'rating': 7}]

Solution 2:[2]

There is no direct solution to this problem. But you can use following code:

a = [{'id':1, 'name':'John Doe'}, {'id':2, 'name':'Jane Doe'}]
b = [{'id':1, 'rating':9}, {'id':2, 'rating':7}, {'id':3, 'rating':8}]
key_pos_mapping = {}
for index,dict in enumerate(a):
    key_pos_mapping[dict['id']] = index
 
for dict in b:
    if( dict['id'] in key_pos_mapping.keys()):
        dict.update(a[key_pos_mapping[dict['id']]])
    else:
        b.remove(dict)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomer Hanochi
Solution 2 Paridhi Gupta