我正在尝试使用for循环从json中提取有关多个城市天气模式的数据,并将所述数据输入到dataframe df\u cities中:
units = 'imperial'
params = {'appid': api_key,
'units': units}
for index, row in df_cities.iterrows():
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city = row['Name']
params['q'] = f'{city}'
response = requests.get(base_url, params=params).json()
df_cities.loc[index, 'Temperature'] = response['main']['temp']
df_cities.loc[index, 'Humidity'] = response['main']['humidity']
df_cities.loc[index, 'Cloudiness'] = response['main']['temp']
df_cities.loc[index, 'Windspeed'] = response['wind']['speed']
然而,不管我用什么方式构造循环,我总是得到一个KeyError:'main'。但是如果我在循环外执行response['main]['temp'],就会得到我想要的结果:
citys = 'Chicago'
units = 'imperial'
url = "http://api.openweathermap.org/data/2.5/weather?"
query_url = f'{url}appid={api_key}&q={citys}&units={units}'
response = requests.get(query_url).json()
response['main']['temp']
39.33
为什么python不能识别循环中的json?你知道吗
芝加哥的响应确实包含
main
键,但是在某个点上,您的df_cities.iterrows()
循环会生成其他一些响应中没有main
键的城市。你知道吗您可以在尝试访问
main
之前检查它的存在:相关问题 更多 >
编程相关推荐