我正在使用API提取此列表。我需要用户能够输入航空公司的“名称”。然后,一旦捕获到名称,则将“名称”与同一词典中的“ icao”代码匹配。
我的密码
import requests
api-url= ("https://api.url")
class airlinenames(Component):
def start(self):
name = "Ali Airlines"
url = API_URL
data = requests.get(url).json()
icao = data['airlines'][0]['icao']
text = ( "this is your airline: {name} and this is the icao code: {icao}"
).format(
name=name,
icao=icao
)
message = self.create_message(text=text)
return self.respond(message=message, action="next"
我的问题是,与其从同一词典中提取匹配的“ icao”,不如将其排在顶部。
因此,例如,如果用户输入“ Ali航空公司”,它应显示为“这是您的航空公司:Ali航空公司,您的ICAO代码是:ALI
示例列表:
{
"airlines": [
{
"fs": "BS",
"iata": "BS",
"icao": "ALI",
"name": "Ali Airlines",
"active": true
},
{
"fs": "BS*",
"iata": "BS",
"icao": "BAL",
"name": "Bali Airline",
"active": true
},
{
"fs": "BSK",
"iata": "LL",
"icao": "GAL",
"name": "Gali airline",
"active": true
}
]
}
当前,在您提供的代码中,您始终可以获得第一家航空公司(data ['airlines'] [0])。
相反,您可能应该先将数据转换成以航空公司名称为关键字的字典,例如:
airlines = { a['name'] : a for a in data['airlines']}
现在,有了该字典和name变量,您可以找到相应的代码:
icao = airlines[name]['icao'] # This will give you the code give a name.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句