Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update list of dictionary from another list of dictionary python

Tags:

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.

like image 267
Andrew Tran Avatar asked Dec 19 '25 10:12

Andrew Tran


1 Answers

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())
like image 136
Mad Physicist Avatar answered Dec 20 '25 22:12

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!