【问题标题】:Looping through list of dicts and appending to csv file - index error循环遍历字典列表并附加到 csv 文件 - 索引错误
【发布时间】: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


【解决方案1】:

问题是

  • i 是一个索引
  • data[i] 是一项,dict
  • x 是 data[i] 字典的一个键,第一个是 'name'
  • x[1] 是字母 n,...x[3] 是字母 'e',所以 x[4] 超出范围

只要写下你已经拥有的字典

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 item in data:
        writer.writerow(item)

或者直接使用pandas

import pandas as pd

df = pd.DataFrame(data)
df.to_csv('Meteroits.csv', index=False)

【讨论】:

    【解决方案2】:

    错误是x 是字典的键,而不是字典本身。应该是:

    for i in range(len(data)):
        new_dict = {}
        for x, val in data[i].items():
            new_dict[x] = val
        writer.writerow(new_dict)
    

    【讨论】:

    • 你只是在复制字典,同样的方式
    • 同意,我认为 OP 想要解构字典并构建一个新字典是有原因的。
    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多