Python TypeError:列表索引必须是整数或片,而不是str,Django 3.1 CLOSED

2024-09-30 20:23:09 发布

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

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

为什么在调用OpenWetherMap API的“weather”对象时会出现如下错误:

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)

Tags: importinfoapicitymainresdescriptionrender
1条回答
网友
1楼 · 发布于 2024-09-30 20:23:09

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

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

相关问题 更多 >