从Python字典获取项数据时出错

2024-03-28 18:12:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读取一个json文件,从openweathermap检索,以获取某个位置的预期温度和降雨量。 下面是json file的一个例子

我有一个循环来检索每个索引,我可以得到除rain以外的任何值

result_data = []
result_tmax = []
result_prec = []
for item in data['list']:
   time = item['dt_txt']
   temperature = item['main']['temp_max']
   prec = item['rain']['3h']
   result_data.append(time)
   result_tmax.append(temperature)
   result_prec.append(prec)

我´我得到

KeyError: 'rain'

如果不下雨,效果很好:

    future_date     future_temp
0   2019-10-17 12:00:00     18.45
1   2019-10-17 15:00:00     19.48
2   2019-10-17 18:00:00     17.03
3   2019-10-17 21:00:00     16.44
4   2019-10-18 00:00:00     15.67
5   2019-10-18 03:00:00     14.77

提前谢谢你


Tags: 文件jsondatatimefutureresult温度item
2条回答

这是我的API调用,不是我传递的示例(抱歉搞错了):

 'list': [{'dt': 1571335200,
 'main': {'temp': 16.04,
'temp_min': 16.04,
'temp_max': 16.84,
'pressure': 1016,
'sea_level': 1016,
'grnd_level': 997.149,
'humidity': 87,
'temp_kf': -0.81},
 'weather': [{'id': 500,
 'main': 'Rain',
 'description': 'light rain',
 'icon': '10n'}],
 'clouds': {'all': 96},
 'wind': {'speed': 2.122, 'deg': 308.301},
 'rain': {'3h': 0.563},
 'sys': {'pod': 'n'},
'dt_txt': '2019-10-17 18:00:00'},
{'dt': 1571346000,
'main': {'temp': 15.74,
'temp_min': 15.74,
'temp_max': 16.35,
'pressure': 1018,
'sea_level': 1018,
'grnd_level': 998.455,
'humidity': 83,
'temp_kf': -0.61},
'weather': [{'id': 804,
 'main': 'Clouds',
 'description': 'overcast clouds',
 'icon': '04n'}],
'clouds': {'all': 97},
'wind': {'speed': 2.292, 'deg': 325.325},
'sys': {'pod': 'n'},
'dt_txt': '2019-10-17 21:00:00'}

2019-10-17 18:00:00有雨,21:00:00无雨,项目有雨

有人有办法解决这个问题并避免错误吗

在你给的链接中没有找到任何“雨”键 click here. 我想你在找“雪”

请将“雨”替换为“雪”,然后重新测试。会有用的

相关问题 更多 >