Home > other >  Concat 2 list of dictionaries with same id
Concat 2 list of dictionaries with same id

Time:05-22

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

CodePudding user response:

You could use the new merging dictionaries feature introduced in Python 3.9:

>>> 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}]
>>> b_id_to_d = {d['id']: d for d in b}  # Create for O(1) lookup time by id.
>>> b_id_to_d
{1: {'id': 1, 'rating': 9}, 2: {'id': 2, 'rating': 7}, 3: {'id': 3, 'rating': 8}}
>>> c = [d | b_id_to_d.get(d['id'], {'rating': 0}) for d in a]
>>> c
[{'id': 1, 'name': 'John Doe', 'rating': 9}, {'id': 2, 'name': 'Jane Doe', 'rating': 7}, {'id': 4, 'name': 'Sample Doe', 'rating': 0}]

For older versions of Python you can try use dict unpacking instead:

>>> c = [{**d, **b_id_to_d.get(d['id'], {'rating': 0})} for d in a]
>>> c
[{'id': 1, 'name': 'John Doe', 'rating': 9}, {'id': 2, 'name': 'Jane Doe', 'rating': 7}, {'id': 4, 'name': 'Sample Doe', 'rating': 0}]

CodePudding user response:

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

CodePudding user response:

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)
  • Related