Andrew Tran
Andrew Tran

Reputation: 57

Update list of dictionary from another list of dictionary python

list1 = [
    {"code": 1, "a": 7, "b": 9, "c": 24},
    {"code": 2, "a": 78, "b": 12, "c": 45},
    {"code": 3, "a": 3, "b": 5, "c": 16}
]
list2=[
    {"code": 1, "a": 45, "b": 21, "c": 24},
    {"code": 2, "a": 84, "b": 7, "c": 55}
]

Output:

list1 = [
    {"code": 1, "a": 45, "b": 21, "c": 24},
    {"code": 2, "a": 84, "b": 7, "c": 55},
    {"code": 3, "a": 3, "b": 5, "c": 16}
]

I need to update list1 based on list2 with the same key "code". I tried:

update_mapping = {k["code"]: k for k in list2}
list1 = [update_mapping.get(k["code"], k) for k in list1]

but it did not work.

Upvotes: 3

Views: 116

Answers (2)

S.B
S.B

Reputation: 16476

Assume that your lists are in correct order, another solution is to simply iterate over each item in the list1 and update it with the corresponding item in list2:

for item_1, item_2 in zip(list1, list2):
    item_1.update(item_2)

Also bear in mind the point "Mad" said about insertion order in dictionaries for python 3.6-

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114230

As with any lookup problem, dictionaries are your friend. Transform your list into something keyed by code:

d1 = {d['code']: d for d in list1}
d2 = {d['code']: d for d in list2}
d1.update(d2)
list1 = list(d1.values())

Dictionaries are ordered in Python 3.6+, and update preserves key order, so this would work perfectly. For prior versions, use collections.OrderedDict (which is still available in Python 3.6+):

from collections import OrderedDict

d1 = OrderedDict((d['code'], d) for d in list1)
d2 = OrderedDict((d['code'], d) for d in list2)
d1.update(d2)
list1 = list(d1.values())

Upvotes: 2

Related Questions