简体   繁体   中英

how to update dictionaries inside two seperate lists?

I have two list:

list1 = [{"name":"xyz" ,"roll":"r" , "sap_id":"z"} , {"name":"pqr" ,"roll":"s" , "sap_id":"w"}]
list2 = [{"cn_number":"26455"} , {"cn_number":"26456"}]

I want a new list like:

new_list = [{"name":xyz ,"roll":"r" , "sap_id":"z","cn_number":"26455"} , {"name":"pqr" ,"roll":"s" , "sap_id":"w","cn_number":"26456"}]

I tried the following method:

new_list = [i.update(j) for i, j in zip(list1, list2)]

but got some nasty error

This syntax works for python3.5 and above to merge two dictionaries z = {**x, **y}

Python 3.7.0 (default, Jun 28 2018, 13:15:42)
>>> list1 = [{"name":"xyz" ,"roll":"r" , "sap_id":"z"} , {"name":"pqr" ,"roll":"s" , "sap_id":"w"}]
>>> list2 = [{"cn_number":"26455"} , {"cn_number":"26456"}]
>>> new_list = [{**i, **j} for i, j in zip(list1, list2)]
>>> new_list
[{'name': 'xyz', 'roll': 'r', 'sap_id': 'z', 'cn_number': '26455'}, {'name': 'pqr', 'roll': 's', 'sap_id': 'w', 'cn_number': '26456'}]

More information: How do I merge two dictionaries in a single expression (take union of dictionaries)?

You can use the Python 3.5+ dict merging syntax:

new_list = [{**a, **b} for (a, b) in zip(list1, list2)]

results in

[
  {'name': 'xyz', 'roll': 'r', 'sap_id': 'z', 'cn_number': '26455'}, 
  {'name': 'pqr', 'roll': 's', 'sap_id': 'w', 'cn_number': '26456'},
]

An efficient way to do this is with collections.ChainMap which is made specifically for combining multiple dictionaries. Read more on the documentation here .

from collections import ChainMap

[dict(ChainMap(i,j)) for i,j in zip(list1, list2)]
[{'cn_number': '26455', 'name': 'xyz', 'roll': 'r', 'sap_id': 'z'},
 {'cn_number': '26456', 'name': 'pqr', 'roll': 's', 'sap_id': 'w'}]

NOTE: Depending on how you want to use each element of the updated list, you could use a generator and avoid using dict() over ChainMap object to still get what you need without using unnecessary memory! ChainMap gives you a single updatable view of the multiple dictionaries by still referencing the original objects.

#efficient way -

g = (ChainMap(i,j) for i,j in zip(list1, list2))

next(g).get('sap_id')
z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM