I want to search a tuple of tuples
for a particular string and return the index of the parent tuple. I seem to run into variations of this kind of search frequently.
What is the most pythonic way to do this?
I.E:
derp = (('Cat','Pet'),('Dog','Pet'),('Spock','Vulcan'))
i = None
for index, item in enumerate(derp):
if item[0] == 'Spock':
i = index
break
>>>print i
2
I could generalize this into a small utility function that takes an iterable, an index (I've hard coded 0
in the example) and a search value. It does the trick but I've got this notion that there's probably a one-liner for it ;)
I.E:
def pluck(iterable, key, value):
for index, item in enumerate(iterable):
if item[key] == value:
return index
return None
It does the trick but I've got this notion that there's probably a one-liner for it ;)
The one-liner is probably not the pythonic way to do it :)
The method you have used looks fine.
Edit:
If you want to be cute:
return next( (i for i,(k,v) in enumerate(items) if k=='Spock'),None)
next
takes a generator expression and returns the next value or the second argument (in this case None
) once the generator has been exhausted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With