继续获取KeyError:“main”,尽管代码工作正常

2024-04-27 04:34:58 发布

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

我正在尝试使用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?你知道吗


Tags: 数据apijsonurldfforindexmain
1条回答
网友
1楼 · 发布于 2024-04-27 04:34:58

芝加哥的响应确实包含main键,但是在某个点上,您的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)

相关问题 更多 >