【发布时间】:2017-05-01 18:28:16
【问题描述】:
我有一个偶尔为空或不存在的数组。我不断收到一条错误消息,说它不存在,但显然存在。这是错误消息:
Traceback(最近一次调用最后一次): 文件“C:\Users\ab67322\Desktop\python\Weather\weatheropen1.1.py”,第 23 行,在 雨 = n['雨'] KeyError: '雨'
非常感谢任何帮助。
NMNorthzip=[87401,87301]
for x in NMNorthzip:
r = requests.get("http://api.openweathermap.org/data/2.5/forecast?zip="+str(x)+",us&appid=id")
data = r.json()
forecast = data['list']
pprint(forecast)
for n in forecast:
if n['rain'] is None:
print ("empty")
else:
print(n['rain'])
输出>>>
{'clouds': {'all': 92},
'dt': 1494093600,
'dt_txt': '2017-05-06 18:00:00',
'main': {'grnd_level': 822.44,
'humidity': 62,
'pressure': 822.44,
'sea_level': 1018.05,
'temp': 292.882,
'temp_kf': 0,
'temp_max': 292.882,
'temp_min': 292.882},
'rain': {'3h': 0.125},
'sys': {'pod': 'd'},
'weather': [{'description': 'light rain',
'icon': '10d',
'id': 500,
'main': 'Rain'}],
'wind': {'deg': 143.002, 'speed': 3.11}}]
【问题讨论】:
-
缺少什么数组会引发异常?您能否将异常消息放入您的问题中,以便我们理解问题?
-
n['rain'] 是错误。我会更新帖子。
标签: python arrays json for-loop