Я пытаюсь извлечь из json данные о погодных условиях в нескольких городах, используя цикл for, и ввести эти данные в фрейм данных 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'. Но если я выполню ответ ['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 внутри цикла?