Comparing String from Dictionary to Multiple Strings

Question:

I’m receiving a dictionary from a server and have a few expected values to get back, however there are times that I get values I don’t want to process my code for. Is there a way I can do this check without needing to repeat dict["travel"] !=

if dict["travel"] != "Bee" and dict["travel"] != "Fly" and dict["travel"] != "Bird":
    print("Didn't receive flying animal of choice")
    return

Ideally my code would look like…

if dict["travel"] != ("Bee" or "Fly" or "Bird")
    print("Didn't receive flying animal of choice")
    return
Asked By: brett s

||

Answers:

checks if dict["travel"] is not present in the list ["Bee", "Fly", "Bird"].
You can try this code:

if dict["travel"] not in ["Bee", "Fly", "Bird"]:
    print("Didn't receive flying animal of choice")
    return
Answered By: ma9

If you want to check if either A, B, or C is in X, you do:

if X in [A, B, C]

In your case this is:

if not dict['travel'] in ['Bee', 'Fly', 'Bird']

To check the opposite, remove the not keyword

if dict['travel'] in ['Bee', 'Fly', 'Bird']
Answered By: Antosser
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.