Python类型错误:列表索引必须是整数或切片,而不是str,Django 3.1 CLOSED


city_info = {
'city': city,
'temp': res['main']['temp'],
'weatherDescription': res['weather']['description'],
'icon': res['weather']['icon'],
'windSpeed': res['wind']['speed'],
}

为什么当我调用OpenWetherMap API的"天气"对象时,我会出现以下错误:

TypeError: list indices must be integers or slices, not str

我使用的是Python 3.8.2和Django 3.1

完整代码,如下所示:

from django.shortcuts import render
import requests
def index(request):
# This is MINE API key! You can change it to yours, if you need it.
apiKey = '8bf70752121d2f2366e66d73f3445966'
url = 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + apiKey 
city = 'Washington'
res = requests.get(url.format(city)).json()
city_info = {
'city': city,
'temp': res['main']['temp'],
'weatherDescription': res['weather']['description'],
'icon': res['weather']['icon'],
'windSpeed': res['wind']['speed'],
}
context = {'info': city_info}
return render(request, 'weather/index.html', context)

res['weather']是一个包含字典的列表,因此只需执行以下操作:

city_info = {
'city': city,
'temp': res['main']['temp'],
'weatherDescription': res['weather'][0]['description'],
'icon': res['weather'][0]['icon'],
'windSpeed': res['wind']['speed'],
}

相关内容

  • 没有找到相关文章

最新更新