Python中的索引必须是“接收错误字符串中的整数:types”

2024-04-27 00:32:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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

Tags: 文件theinfromimportjsonurl编码
2条回答

问题出在temp_krecord['temp']的这一部分。在

这是每个变量record的格式:

for record in url2 ['main']:
    print record

>> pressure
temp_min
temp_max
temp
humidity

您正试图将一组字符串作为字典索引,因此字符串索引错误。只需将temp_k行改为:

^{pr2}$

数据中main的值是dict,而不是dict列表。因此,不需要迭代它;只需直接访问temp值。在

temp_k = url2['main']['temp'] 

相关问题 更多 >