[ACCEPTED]-Looking for values in nested tuple-python

Accepted answer
Score: 10

The elements of a tuple can be extracted 5 by specifying an index: ('a', 'b')[0] == 'a'. You can use a 4 list comprehension to iterate over all elements of some iterable. A 3 tuple is also iterable. Lastly, any() tells whether 2 any element in a given iterable evaluates 1 to True. Putting all this together:

>>> t = (
...     ('dog', 'Dog'),
...     ('cat', 'Cat'),
...     ('fish', 'Fish'),
... )
>>> def contains(w, t):
...     return any(w == e[0] for e in t)
... 
>>> contains('fish', t)
True
>>> contains('dish', t)
False
Score: 5

Try:

any('fish' == tup[0] for tup in t)

EDIT: Stephan is right; fixed 'fish' == tup[0]. Also 1 see his more complete answer.

Score: 3

When you have an iterable of key-value pairs 4 such as:

t = (
    ('dog', 'Dog'),
    ('cat', 'Cat'),
    ('fish', 'Fish'),
)

You can "cast" it to a 3 dictionary using the dict() constructor, then 2 use the in keyword.

if 'fish' in dict(t):
    print 'fish is in t'

This is very similar to 1 the above answer.

Score: 2

You could do something like this:

if 'fish' in (item[0] for item in t):
    print "Fish in t."

or this:

if any(item[0] == 'fish' for item in t):
    print "Fish in t."

If 3 you don't care about the order but want 2 to keep the association between 'dog' and 'Dog', you 1 may want to use a dictionary instead:

t = {
    'dog': 'Dog',
    'cat': 'Cat',
    'fish': 'Fish',
}

if 'fish' in t:
    print "Fish in t."

More Related questions