尽管代码在其他地方工作,但仍然不断收到KeyError:'main'

时间:2019-01-06 21:13:41

标签: python json url

我正在尝试使用for循环从json中提取有关几个城市天气模式的数据,并将所述数据输入到数据框df_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?

1 个答案:

答案 0 :(得分:0)

Chicago的响应确实包含df_cities.iterrows()键,但是在某个时候,您的main循环会在其他城市中产生一个没有main键的城市。

您可以在尝试访问if 'main' in response: 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'] else: print('main key not in response JSON for city %s' % city) 之前检查其是否存在:

{{1}}