Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a 2-Dimensional Tuple/List in Python

Tags:

python

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
like image 603
Koobz Avatar asked Feb 27 '23 15:02

Koobz


1 Answers

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.

like image 141
HS. Avatar answered Mar 03 '23 07:03

HS.