0

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?

DrStrangepork
  • 2,955
  • 2
  • 27
  • 33
  • Since, you are using list comprehension, your output for `Id` is supposed to be a list, so if there is only one element, then it would be this `Id == ['1']`. If you know that only one `Id` has the `name 'foo'`, then you can just use a for loop. So if your condition gets True, then Id will be saved into the `Id` variable, otherwise not. – Sarques Dec 06 '19 at 20:52
  • 1
    Does this answer your question? [Get the first item from an iterable that matches a condition](https://stackoverflow.com/questions/2361426/get-the-first-item-from-an-iterable-that-matches-a-condition) – Patrick Haugh Dec 06 '19 at 20:54

1 Answers1

0

You can use a generator:

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

The added benefit is that the iteration will be stopped as soon as you encounter matching object, whereas your original code would process all of the original list and create a new one, only to extract its first element.

wgslr
  • 76
  • 1
  • 4