首页 > 解决方案 > 如何将相同的函数应用于字典数组中的每个值?

问题描述

我正在使用 Python 3.7。我有一个字典数组,每个数组都有相同的键。例如

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

如何将相同的函数应用于每个字典中的某个键的值?例如,我想将大写函数应用于上述值

arr_of_dicts = ({"st" : "IL"}, {"st" : "IL"}, {"st" : "IL"})

?

标签: pythonarrayspython-3.xdictionary

解决方案


使用map(),您可以使您的转换函数接受一个键来转换并返回一个 lambda,它充当映射方法。通过使用之前传递的键 ( k) 和传入的字典 ( d),您可以返回一个新字典,并将字典的值转换为大写:

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

upper = lambda k: lambda d: {k: d[k].upper()} # your func
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

结果:

[{'st': 'IL'}, {'st': 'IL'}, {'st': 'IL'}]

如果您的字典有额外的键,那么您可以首先将原始字典传播到新字典中,然后用大写版本覆盖您要转换的键属性,如下所示:

arr_of_dicts = [{"a": 5, "st" : "il"}, {"a": 7, "st" : "IL"}, {"a": 8, "st" : "Il"}]

upper = lambda k: lambda d: {**d, k: d[k].upper()}
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

结果:

[{'a': 5, 'st': 'IL'}, {'a': 7, 'st': 'IL'}, {'a': 8, 'st': 'IL'}]

推荐阅读