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

Time:05-25

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.

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?

CodePudding user response:

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.

  • Related