Method returns TypeError: list indices must be integers or slices, not str
Method returns TypeError: list indices must be integers or slices, not str
我正在使用 openweathermap 获取天气数据,其中 returns 一个 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"]
有人有什么建议吗?
应该是
class OpenWeather:
def descrip(self):
return self.data["weather"][0]["description"]
# ^^^
或者某种列表理解,因为 weather
是一个列表(可能是字典列表,但您的示例只包含一个字典)。
我正在使用 openweathermap 获取天气数据,其中 returns 一个 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"]
有人有什么建议吗?
应该是
class OpenWeather:
def descrip(self):
return self.data["weather"][0]["description"]
# ^^^
或者某种列表理解,因为 weather
是一个列表(可能是字典列表,但您的示例只包含一个字典)。