【发布时间】:2022-01-05 02:34:48
【问题描述】:
我正在尝试通过循环遍历列表然后循环遍历 json 数据的字典来将值附加到 csv 文件,但我得到一个索引错误:
import csv
data=json_resp.json()
with open('Meteroits.csv','w+') as file:
writer=csv.DictWriter(file,fieldnames=['name','id','nametype','recclass','mass','fall','year','reclat','reclong','geolocation'])
writer.writeheader()
for i in range(len(data)):
for x in data[i]:
name=x[1]
i_d=x[2]
nametype=x[3]
recclass=x[4]
mass=x[5]
fall=x[6]
year=x[7]
reclat=x[8]
reclong=x[9]
geolocation=x[10]
writer.writerow({'name':name,'id':i_d,'nametype':nametype,'recclass':recclass,'mass':mass,'fall':fall,'year':year,'reclat':reclat,'reclong':reclong,'geolocation':geolocation})
我在index 4 收到错误:
---> 12 recclass=x[4]
IndexError: string index out of range
这是一个数据样本:
{
'name': 'Abee',
'id': '6',
'nametype': 'Valid',
'recclass': 'EH4',
'mass': '107000',
'fall': 'Fell',
'year': '1952-01-01T00:00:00.000',
'reclat': '54.216670',
'reclong': '-113.000000',
'geolocation': {'latitude': '54.21667', 'longitude': '-113.0'}
}
【问题讨论】:
-
您的索引似乎从 1 开始。如果您显示 IndexError 发生的位置,则更容易发表评论。
-
您的数据样本不符合您将 json 内容描述为“字典列表”的描述。
标签: python api for-loop index-error