方法返回TypeError:列表索引必须是整数或片,而不是str

2024-05-11 04:09:18 发布

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

我使用openweathermap获取天气数据,它返回一个JSON对象,如下所示:

blank = {
    "coord": {"lon": -92.11, "lat": 46.78},
    "weather": [
        {"id": 800, "main": "Unknown", "description": "Unknown", "icon": "01d"}
    ],
    "base": "stations",
    "main": {
        "temp": 0,
        "feels_like": 0,
        "temp_min": 0,
        "temp_max": 0,
        "pressure": 0,
        "humidity": 0,
    },
    "visibility": 0,
    "wind": {"speed": 0, "deg": 0},
    "clouds": {"all": 1},
    "dt": 0,
    "sys": {"type": 1, "id": 3903, "country": "US", "sunrise": 0, "sunset": 0},
    "timezone": 0,
    "id": 0,
    "name": "Unknown",
    "cod": 0,
}

我在["weather"]["description"]上返回字符串时遇到问题。这将引发类型错误TypeError: list indices must be integers or slices, not str

方法:

class OpenWeather:
    def descrip(self):
        return self.data["weather"]["description"]

有人要小费吗


Tags: 数据对象selfidjsonmaindescriptiontemp
1条回答
网友
1楼 · 发布于 2024-05-11 04:09:18

应该是

class OpenWeather:
    def descrip(self):
        return self.data["weather"][0]["description"]
        #                          ^^^

或者某种列表理解,比如weather是一个列表(可能是一个字典列表,但您的示例只包含一个字典)

相关问题 更多 >