OpenWeatherMap空气质量API JSON数据访问报错:TypeError: list indices must be integers or slices, not str
解决OpenWeatherMap Air Pollution API数据访问的TypeError问题
嘿,我来帮你搞定这个报错!咱们先拆解一下问题出在哪:
错误原因分析
你遇到的TypeError: list indices must be integers or slices, not str,核心问题是你把列表当成字典来访问了。
看你用pprint输出的air_data结构:
{'coord': {'lat': MY_LAT, 'lon': MY_LON}, 'list': [{'components': {...}, 'dt': 1640822400, 'main': {'aqi': 1}}]}
注意到'list'对应的是一个方括号包裹的列表,里面只包含1个字典元素。而你写的air_data['list']['main']是试图用字符串'main'去索引列表,这显然不符合Python列表的访问规则——列表只能用整数索引(比如[0])或者切片来取值。
至于你说其他Weather API能用类似写法,大概率是那些API的list字段本身就是字典结构,而非列表,所以访问方式不同。
修正后的代码
只需要在list后面加上索引[0],先取出列表里的唯一字典元素,再去访问main和aqi:
import requests URL = "http://api.openweathermap.org/data/2.5/air_pollution?lat=MY_LATITUDE&lon=MY_LONGITUDE&appid=MY_API_KEY" air_data = requests.get(URL).json() # 先取列表的第一个元素(索引0),再访问main里的aqi aqi = air_data['list'][0]['main']['aqi'] print(aqi, 'AirQualityIndex')
如果之后API返回多个时间点的空气质量数据(比如你指定了历史范围),list里会有多个字典元素,你可以用循环遍历它们:
for entry in air_data['list']: print(entry['dt'], entry['main']['aqi'])
内容的提问来源于stack exchange,提问作者ShadowHunterz
相关产品推荐
相关产品推荐

