【问题标题】:"list indices must be integers" error, when trying to use keys from a dictionary尝试使用字典中的键时出现“列表索引必须是整数”错误
【发布时间】: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


【解决方案1】:

根据 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"])

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多