【发布时间】:2019-03-12 18:43:31
【问题描述】:
我尝试在 python 中使用openweathermap.org rest 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)
【问题讨论】:
-
你能分享一下你遇到了什么错误吗?
-
jputha["coord"]返回与键"coord"关联的值,在这种情况下,它看起来是一个列表。然而,列表不能由其元素索引,只能由整数索引。要进一步分析您的问题,您应该指定您的lokka用户输入。
标签: python json api typeerror openweathermap