Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

Python/JSON : I want to go to a specific thing when it can't find it in a json file

I'm actually making my discord bot and I wanted to make a command to know plane informations. I made it but know i want to put plane photos depending on the company. I tried to do that:

if plane_data["data"][f"{flight_companie}"] == "FedEx" or "Ryanair" or "SWISS" or "Air France" or "SWISS" or "British Airways":
  plane_photo = plane_data["data"][flight_companie]
else:
  plane_photo = plane_data["data"]["unknown"]

Unknown is equal to a url photo that says there is no plane photos.

When i try with UPS it gives me that out:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'UPS Airlines'

Please help me out!!

question from:https://stackoverflow.com/questions/66050967/python-json-i-want-to-go-to-a-specific-thing-when-it-cant-find-it-in-a-json-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
if plane_data["data"][f"{flight_companie}"] == "FedEx" or "Ryanair"...

will always evaluate to True. This is because a string like "Ryanair" is truthy. Meaning it becomes true when converted to a boolean. So your line is equivialent to

if plane_data["data"][f"{flight_companie}"] == "FedEx" or True or True or True ...

or can not be used in this situation. I would use

if plane_data["data"][f"{flight_companie}"] in ["FedEx","Ryanair","SWISS","Air France","SWISS","British Airways"]:

instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...