《Python编程:快速上手》OpenWeatherMap API示例KeyError问题求助
问题:OpenWeatherMap API调用出现KeyError: 'list'错误
问题背景
学习《Python编程:快速上手》(Automate the boring stuff)第16章的天气预报示例时,因原示例涉及的API功能可能已不在免费订阅范围内,改用免费可用的接口后,执行w = weatherData['list']时触发KeyError: 'list'错误。返回的JSON数据结构如下:
{ 'coord': {'lon': -0.1257, 'lat': 51.5085}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 296.2, 'feels_like': 295.87, 'temp_min': 294.35, 'temp_max': 297.64, 'pressure': 1020, 'humidity': 50}, 'visibility': 10000, 'wind': {'speed': 2.57, 'deg': 240}, 'clouds': {'all': 55}, 'dt': 1694696224, 'sys': {'type': 2, 'id': 268730, 'country': 'GB', 'sunrise': 1694669592, 'sunset': 1694715572}, 'timezone': 3600, 'id': 2643743, 'name': 'London', 'cod': 200 }
报错信息:
Traceback (most recent call last): File "c:\users\andrea\mu_code\16_delete.py", line 21, in w = weatherData['list'] KeyError: 'list'
原代码:
#! python3 # 16_getOpenWeather.py - prints the weather for a location # obviously not the real AppID ;-) APPID = '12345' import json, requests location = 'London, UK' # Download the JSON data from OpenWeatherMap.org's API url = 'https://api.openweathermap.org/data/2.5/weather?q=%s&APPID=%s' %(location, APPID) response = requests.get(url) response.raise_for_status() # Load JSON data into a python variable weatherData = json.loads(response.text) print(weatherData) # Print weather descriptions w = weatherData['list'] print('Current weather in %s: ' % (location)) print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
问题分析
- 原代码中的
weatherData['list']是针对5天天气预报接口(/data/2.5/forecast)的返回结构设计的,该接口返回的JSON包含list字段,是一个包含多时段天气数据的列表。但你现在调用的是当前天气接口(/data/2.5/weather),这个接口的返回结构里没有list字段,所以会触发KeyError。 - 当前天气接口的天气描述直接存储在顶层的
weather字段中(是一个列表,支持同时返回多个天气状况),无需通过list层级访问。
修改后的代码
#! python3 # 16_getOpenWeather.py - prints the current weather for a location # 替换为你的真实AppID APPID = '12345' import json, requests location = 'London, UK' # 调用当前天气接口 url = 'https://api.openweathermap.org/data/2.5/weather?q=%s&APPID=%s' %(location, APPID) response = requests.get(url) response.raise_for_status() # 解析JSON数据 weatherData = json.loads(response.text) # 打印当前天气描述 print(f'Current weather in {location}: ') # 从weather字段中获取第一个天气状况(通常只有一个) current_weather = weatherData['weather'][0] print(f'{current_weather["main"]} - {current_weather["description"]}') # 可选:打印温度信息(转换为摄氏度,原数据是开尔文) temp_celsius = weatherData['main']['temp'] - 273.15 print(f'Temperature: {temp_celsius:.1f}°C') print(f'Feels like: {weatherData["main"]["feels_like"] - 273.15:.1f}°C')
内容的提问来源于stack exchange,提问作者Schlossie
相关产品推荐
相关产品推荐

