Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update dictionaries inside two separate 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

like image 968
Animesh Singh Avatar asked Jan 01 '22 01:01

Animesh Singh


People also ask

How do you update a dictionary with multiple values?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.


Video Answer


3 Answers

This syntax works for python3.5+ 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)?

like image 195
Kamel Avatar answered Oct 24 '22 07:10

Kamel


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'},
]
like image 45
AKX Avatar answered Oct 24 '22 06:10

AKX


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 -

#EDITED: lesser keystrokes as suggested by @Kelly
g = map(ChainMap, list1, list2) 

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

next(g).get('sap_id')
z
like image 25
Akshay Sehgal Avatar answered Oct 24 '22 07:10

Akshay Sehgal