brüto
brüto

Reputation: 15

'if' 'or'- statement in dictionary always returns TRUE

I have this python dictionary:

event_dict = {
            'False': 1,
            'Hit': 2,
            'MP1': 3,
            'MP2': 4,
            'MP3': 5,
            'M_False': 6,
            'M_Hit': 7,
            'OGT': 8,
            'PMC': 9,
            'S  4': 10,
            'actiCAP Data On': 11,
            'boundary': 12
 }

And I wrote this code to check if the entries "TriEVE", "TriODD", "TriPMC" are in the dictionary (They're not!):

if "TriEVE" or "TriODD" or "TriPMC" in event_dict:
    print('THIS SESSION HAS BAD ANNOTATIONS!!!!!!!')

The code returns:

THIS SESSION HAS BAD ANNOTATIONS!!!!!!!

I tried to use the 'if'-statement with just one input (without 'or'), like:

if "TriEVE" in event_dict:
    print('THIS SESSION HAS BAD ANNOTATIONS!!!!!!!')
    print(subject)

The code returns nothing, as expected.

Why can't I use 'or'-statements in this case? Is there a smarter way of searching for more than one dictionary entry at once?

Upvotes: 0

Views: 302

Answers (1)

Lauren Hatfield
Lauren Hatfield

Reputation: 26

In this case, you want

if "TriEVE" in event_dict.keys() or "TriODD" in event_dict.keys() or "TriPMC" in event_dict.keys():

this is because anything not-zero or non-None is evaluated to True in Python Since it seems that you wanted to search the keys of the dict, you have to use .keys() or .values() if you want to look at values. The object itself isn't useful in this context

Upvotes: 1

Related Questions