简体   繁体   中英

How can I use list of functions to update the values of a dictionary list?

Let's say I have this list of functions:

funcList = [lambda x: int(x)**2, lambda x: int(x)*3]

How can I update the values of a list of dictionaries like this:

dic = [{'x': '3', 'y': '4'}, {'x': '4', 'y': '5'}]

I have tried using lists of comprehension and functions like map but can't seem to make it work.

Thank you for your help.

You can use zip :

funcList = [lambda x: int(x)**2, lambda x: int(x)*3]
dic = [{'x': '3', 'y': '4'}, {'x': '4', 'y': '5'}]
new_dic = [{a:f(int(i[a])) for a, f in zip(i, funcList)} for i in dic]

Output:

[{'x': 9, 'y': 12}, {'x': 16, 'y': 15}]

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