Pyderman
Pyderman

Reputation: 16189

How to check for the presence of an item in a Python tuple without encountering a ValueError?

For'ing over tuples consisting of (spendCampaign, adset, adcontent) (each value changing on each loop, I want to catch when the last item in the tuple is the same as the last item in a tuple in a saved mapping oldAdMapping (a tuple of tuples).

if adcontent == oldAdMapping[oldAdMapping.index((spendCampaign, adset, adcontent))][2]

I see now that this breaks down with a ValueError (and the equality check doesn't get executed) whenever any (spendCampaign, adset, adcontent) tuple does not actually exist in oldAdMapping.

For dicts, we have the has_key() function that allows us to check if something is a key in the dict while avoiding a KeyError if it's not. Is there something similar for tuples? If not, what's the best way of checking for the presence of an item in a tuple wuthout encountering a ValueError?

Upvotes: 0

Views: 98

Answers (3)

rohithvsm
rohithvsm

Reputation: 94

Put the code in a try except block and ignore the error:

try:
    if adcontent == oldAdMapping[oldAdMapping.index((spendCampaign, adset, adcontent))][2]:
        # do what you want here
except ValueError:
    pass

Upvotes: 0

dsh
dsh

Reputation: 12213

Use the in operator to see if a collection (tuple or list or similar) contains an object.

https://docs.python.org/release/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You could validate if the tuple contains it:

if (spendCampaign, adset, adcontent) in oldAdMapping:
    index = oldAdMapping.index((spendCampaign, adset, adcontent))

And in your condition use index

if adcontent == oldAdMapping[index][2]:
    ...

Upvotes: 1

Related Questions