Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to efficiently updating list of dict key-values with list of value in Python

The objective is to update new key-value in a list of dict, whereby the value is from another nested list.

This can be realised via

ls1=[[1,23],[2,34,5]]
ls2=[dict(t=1),dict(t=1)]
all_data=[]

for x,y in zip(ls1,ls2):
    y['new']=x
    all_data.append(y)

For compactness, I would like to have the for-loop in the form of list comprehension.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

all_data=[y.update({'new':x}) for x,y in zip(ls1,ls2)]

But, by doing so, I got a list of None instead. May I know how to resolve this?

>Solution :

This is because .update() returns None, not the updated dictionary. You can bitwise-OR two dictionaries together (Python >= 3.9) to obtain what you want:

all_data = [y | {'new':x} for x,y in zip(ls1,ls2)]

If you need to support Python < 3.9, you can construct a new dictionary from the .items() of the old one instead:

all_data = [dict(y.items(), new=x) for x,y in zip(ls1,ls2)]

Note that both the above solutions leave the original dictionaries unchanged.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading