"list indices must be integers" 错误,尝试使用字典中的键时

"list indices must be integers" error, when trying to use keys from a dictionary

我尝试使用 python 中的 openweathermap.org 休息 API。当我试图从我用 JSON 数据创建的字典中分配一个键时,发生了这个错误。

-list indices must be integers or slices, not str

我是 python 的新手,我找不到解决这个问题的方法。 我写的代码片段:

import requests
from pprint import pprint

lokka = str(input("What is the location you need information of?"))
#takes the location as "lokka"

hellload = requests.get("http://api.openweathermap.org/data/2.5/weather?q="+ lokka +"&appid=xxxxxxxxxxxxxxxxx&units=metric")
#the rest api's load will be taken to the account of hellload

jputha = hellload.json()
#json data will be converted to a dictionary
#print (jputha)

#---------------------------------------------------------
#from now onward I'll be kickin the hell out the jsons
long = str(jputha["coord"]["lon"])
lat = str(jputha["coord"]["lat"])
wthr = str(jputha["weather"]["main"])
temp = str(jputha["main"]["temp"])
winspd = str(jputha["wind"]["speed"])

print(long)
print(lat)
print(wthr)
print(temp)
print(winspd)

根据 OpenWeatherMap 的 documentation,来自 API 的 JSON 响应如下所示:

{"coord":
{"lon":145.77,"lat":-16.92},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],
"base":"cmc stations",
"main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37},
"wind":{"speed":5.1,"deg":150},
"clouds":{"all":75},
"rain":{"3h":3},
"dt":1435658272,
"sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870},
"id":2172797,
"name":"Cairns",
"cod":200}

其中 weather 键包含一个字典列表而不是一个字典,所以如果你只是想要列表中的第一个天气数据,你应该使用 [0] 来获取第一个索引改为:

wthr = str(jputha["weather"][0]["main"])