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
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
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']
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
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
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']