我正在使用openapi创建一个天气图。我是新的编码意义上的编码,同时从互联网接收数据。在
我收到的错误是:
“回溯(最近的呼叫最后一次): 文件“/home/pi/Python Codes/Weather/CurrentTest3.py”,第7行,中 temp_k=[record['temp']for record in url2['main']\;这一行应该从.Json文件中获取温度信息 文件“/home/pi/Python Codes/Weather/CurrentTest3.py”,第7行,中 temp_k=[record['temp']for record in url2['main']\;这一行应该从.Json文件中获取温度信息 TypeError:字符串索引必须是整数
我不明白为什么我得到这个,我的代码如下。在
from dateutil import parser #imports parser
from pprint import pprint #imports pprint
import requests #imports request
url = requests.get('http://api.openweathermap.org/data/2.5/weather? q=london&APPID=APIKEY') #identifies the url address
pprint(url.json()) #prints .JSON information from address
url2 = url.json() #establishes .Json file as variable
temp_k = [record['temp'] for record in url2 ['main']] #this line should take down the temperature information from the .Json file
print(temp_k) #prints the value for temperature
问题出在
temp_k
,record['temp']
的这一部分。在这是每个变量
record
的格式:您正试图将一组字符串作为字典索引,因此字符串索引错误。只需将
^{pr2}$temp_k
行改为:数据中
main
的值是dict,而不是dict列表。因此,不需要迭代它;只需直接访问temp值。在相关问题 更多 >
编程相关推荐