首页 > 解决方案 > 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?

标签: python-3.x

解决方案


您可以使用生成器

Id = next(api['id'] for api in r['items'] if api['name'] == 'foo')

额外的好处是,一旦遇到匹配的对象,迭代就会停止,而您的原始代码将处理所有原始列表并创建一个新列表,仅提取其第一个元素。


推荐阅读