bayman
bayman

Reputation: 1719

Python update a value in a list of dictionaries from another list of dictionaries

If given two list of dictionaries (score_list and update_list) below, how do I update score_list from the list of dictionaries from update_list?

score_list = [{'id': 1, 'score': 123}, {'id': 2, 'score': 234}, {'id': 3, 'score': 345}]

update_list = [{'id': 1, 'score': 500}, {'id': 3, 'score': 300}]

# return this
score_list = [{'id': 1, 'score': 500}, {'id': 2, 'score': 234}, {'id': 3, 'score': 300}]

Upvotes: 3

Views: 52

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

I highly recommend using a mapping when you have a unique key to match:

update_mapping = {d['id']: d for d in update_list}
score_list = [update_mapping.get(d['id'], d) for d in score_list]

Upvotes: 3

Related Questions