mk8efz
mk8efz

Reputation: 1424

Update list of dicts with keys/values from another list of dicts

Assume two list of dicts:

leads and customers where len(customers) < len(leads):

customers = [{'name': 'Joe', 'age': 28}, {'name': 'Adam', 'age': 34}]

leads     = [{'name': 'Joe', 'city': 'NYC'}, {'name': 'Molly', 'city': 'LA'}, 
             {'name': 'Adam', 'city': 'Washington DC'}]

I need to update the customers dict with additional information from leads is the names match:

Desired output:

output = [{'name': 'Joe', 'age': 28, 'city':'NYC'}, {'name': 'Adam', 'age': 34, 'city': 'Washington DC'}]

I've tried zip() and then looping through to match keys, but since they are lists, I'm getting a "list indices must be integers, not str" error

Upvotes: 0

Views: 1724

Answers (2)

Israel Unterman
Israel Unterman

Reputation: 13510

Here is my call on this:

for d in customers:
    lead = [x for x in leads if x['name'] == d['name']]
    if lead:
        d.update(lead[0])

print(customers)

>>>
[{'city': 'NYC', 'age': 28, 'name': 'Joe'}, {'city': 'Washington DC', 'age': 34, 'name': 'Adam'}]

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

You can create a dict using leads list in which the data is stored against the name and later use the name to update the data in customers list.

>>> leads_data = {}
>>> for lead in leads:
...     leads_data.setdefault(lead['name'], {}).update(lead)
...
>>> for c in customers:
...     c.update(leads_data.get(c['name'], {}))
...
>>> customers
[{'city': 'NYC', 'age': 28, 'name': 'Joe'},
 {'city': 'Washington DC', 'age': 34, 'name': 'Adam'}]

Upvotes: 1

Related Questions