python - API 调用检查是否检索到某些数据
问题描述
我在 100 个不同的城市执行 100 次 API 调用,当它被调用时,它通常以以下形式出现:
{'data': {'aqi': 13,
'attributions': [{'name': 'Air Quality Ontario - the Ontario '
'Ministry of the Environment and Climate '
'Change',
'url': 'http://www.airqualityontario.com/'},
{'name': 'World Air Quality Index Project',
'url': 'https://waqi.info/'}],
'city': {'geo': [43.653226, -79.3831843],
'name': 'Toronto',
'url': 'https://aqicn.org/city/toronto'},
'debug': {'sync': '2019-06-04T15:37:48+09:00'},
'dominentpol': 'pm25',
'iaqi': {'co': {'v': 1.7},
'no2': {'v': 15.2},
'o3': {'v': 8.8},
'p': {'v': 1018.3},
'pm25': {'v': 13},
'so2': {'v': 0.2},
't': {'v': 11.6},
'w': {'v': 0.2}},
'idx': 5914,
'status': 'ok'}
然而,在 ['data']['iaqi'] 中,有时它缺少 co、no2、o3 等之一...在循环 100 个城市并执行 api 调用时,我想检查它们是否存在并附加“na “如果它不存在。
我正在尝试,除了这样:
cities = []
aqi = []
# 5 pollutants used to calculate AQI
CO = []
NO2 = []
SO2 = []
pm25 = []
for city in canadian_cities:
city_name = city
url = f'https://api.waqi.info/feed/{city}/?token={api_key}'
response = requests.get(url).json()
if (response["status"] == "ok"):
# sometime aqi might not be a number, exclude them
print("yes")
if (isinstance(response["data"]["aqi"], int)):
# append aqi and city name to appropriate list
aqi.append(response["data"]["aqi"])
cities.append(city)
# append pollutants individually
try:
CO.append(response["data"]["iaqi"]["co"]["v"])
except:
CO.append("na")
try:
NO2.append(response["data"]["iaqi"]["no2"]["v"])
except:
NO2.append("na")
try:
SO2.append(response["data"]["iaqi"]["o3"]["v"])
except:
SO2.append("na")
pm25.append(response["data"]["iaqi"]["pm25"]["v"])
这工作得很好,但似乎效率不高,我想知道是否有更清洁的方法来做到这一点。谢谢!
解决方案
不要将您的 polutants 保存为单独的列表,而是保留这样的字典:
polutants = {"co":[],"no2":[],"so2":[],"pm25":[]}
如果您确保您的密钥与您对 API 的期望相匹配,您现在可以执行以下操作:
for item in polutants.keys():
if item in response["data"]["iaqi"].keys():
polutants[item].append(response["data"]["iaqi"][item])
else:
polutants[item].append('na')
但老实说,你的方式也很好。
推荐阅读
- python - 在 for 循环中对列表进行多线程处理
- javascript - 如何更改打字稿中的“this”指针
- spring-boot - Spring Boot 自定义用户配置文件 url
- arrays - C calloc 和 vla
- java - 使用自定义遥测修复端到端跟踪
- http - 将文件上传转发到其他服务器
- discord - 我想让每个点击我的 Discord oauth 链接的人都被放入服务器
- reactjs - ReactJS 可以在 Symfony 5.3 中使用他们的 Webpack Encore Bundle 在没有节点的情况下运行吗
- reactjs - 如何有条件地禁用输入取决于“React-hook-form”中的另一个输入值?
- java - 使用preparedStatement执行查询时出错