python - 如何将相同的函数应用于字典数组中的每个值?
问题描述
我正在使用 Python 3.7。我有一个字典数组,每个数组都有相同的键。例如
arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})
如何将相同的函数应用于每个字典中的某个键的值?例如,我想将大写函数应用于上述值
arr_of_dicts = ({"st" : "IL"}, {"st" : "IL"}, {"st" : "IL"})
?
解决方案
使用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'}]
推荐阅读
- java - 公开关系 ID 作为 GET、PUT 和 POST REST 调用的 JSON 有效负载的一部分
- c++ - 如何将内存分配给大小为 10^9 的二维数组
- android - 使用滑翔时如何消除从服务器加载图像的延迟?
- three.js - Three.js rev 94 及更高版本中的 VRML 加载器
- powershell - 在 PowerShell 中通过 SFTP 获取文本文件的内容
- antlr4 - 用ANTLR分析包含单引号的引号之间的字符串
- javascript - 我目前正在尝试将任务添加到数组后清除输入字段
- mysql - MySQL全文搜索 - 最小标记大小下的布尔搜索词意味着没有结果回来
- excel - 禁用自动计算
- oracle - 将两行合并为新行并根据值求和