-2

We have two lists in the below format:

list_A = [
    {u'salary': 11, u'id': 1, u'name': u'adam'},
    {u'salary': 22, u'id': 2, u'name': u'ben'},
    {u'salary': 33, u'id': 3, u'name': u'charles'}
]

list_B = [
    {u'salary': 101, u'id': 1, u'name': u'adam'},
    {u'salary': 44, u'id': 4, u'name': u'david'}
]

How do I get id if common in both, then select from list B?

res = [
    {u'salary': 101, u'id': 1, u'name': u'adam'},
    {u'salary': 22, u'id': 2, u'name': u'ben'},
    {u'salary': 33, u'id': 3, u'name': u'charles'},
    {u'salary': 44, u'id': 4, u'name': u'david'}
]

I tried a for loop iterating on list A checking element in B and appending to empty list res, but was not able to achieve the desired result.

id is unique element. list A is old , list B is new, so we have to append the list B to list A overwriting the other elements , in this case, salary is updated for Adam.

Vidya K
  • 103
  • 8

2 Answers2

1

You can put your data in a dictionary and use the update method to make the necessary changes.

list_A = [
    {u'salary': 11, u'id': 1, u'name': u'adam'},
    {u'salary': 22, u'id': 2, u'name': u'ben'},
    {u'salary': 33, u'id': 3, u'name': u'charles'}
]

list_B = [
    {u'salary': 101, u'id': 1, u'name': u'adam'},
    {u'salary': 44, u'id': 4, u'name': u'david'}
]

data = {d['id']: d for d in list_A}
new_data = {d['id']: d for d in list_B}

data.update(new_data)

res = list(data.values())
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
1

Use dictionaries:

by_id = {d['id']: d for d in list_A}
by_id.update({d['id']: d for d in list_B})

You can avoid creating the second dictionary by using a lazy generator:

by_id.update((d['id'], d) for d in list_B)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264