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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With