python-3.x - Get a single key value from a list of maps
问题描述
Given this map
r = {
'items': [
{
'id': '1',
'name': 'foo'
},
{
'id': '2',
'name': 'bar'
}
]
}
I am trying to get the 'id' for 'name'=='foo'. I have this:
Id = [api['id'] for api in r['items'] if 'foo' in api['name']]
But then Id == ['1']
. I want it to = "1". I can do this:
Id = [api['id'] for api in r['items'] if 'foo' in api['name']][0]
But that seems like a workaround. Is there a way to write that in such a way as to pass only the value of api['id']
rather than the value within a list?
解决方案
您可以使用生成器:
Id = next(api['id'] for api in r['items'] if api['name'] == 'foo')
额外的好处是,一旦遇到匹配的对象,迭代就会停止,而您的原始代码将处理所有原始列表并创建一个新列表,仅提取其第一个元素。
推荐阅读
- firebase - 将 React Router 页面视图发送到 Firebase Analytics
- python - TensorFlow 错误和警告
- powerbi - PowerBI - 具有变化值的累积图
- swift - 来自 URL 旋转的 UIImageView 导致图像缩小?(斯威夫特 5,Xcode 11)
- c# - 应用于 html 字符串时替换不起作用
- reactjs - 当我点击图标时如何打开文件上传对话框
- javascript - react native 如何通过npm安装谷歌地图?
- python - 图像未在 django 模板中显示在 django 中是新的并且正在开发一个项目......我已经摆脱了这个错误但没有任何反应
- email - 如何使用 SES 服务在 lambda nodeJs 中发送带有附件的邮件
- php - 重力形式:动态填充字段标签或占位符