繁体   English   中英

字典包含列表,但是当我尝试定位它时出现“IndexError: list index out of range”

[英]Dictionary contains list, but I get 'IndexError: list index out of range' when I try to target it

我有一个以下形式的字典列表:

[{"Title": ["Harry Potter"], "Author": ["J.K.Rowling"]}, 
 {"Title": ["Lord of the Rings"], "Author": ["J.R.R. Tolkien"]}]

我正在尝试使用以下代码将其写入 csv 文件:

for dic in lis:
    title = dict["Title"][0]
    author = dict["Author"][0]

    csvWriter.writerow([title, author])

但是我收到一个 IndexError ,说我的列表索引超出范围。 但是如果我从我的 dict["Title"] 的末尾删除 [0] ......然后它会在我的 csv 文件中放置一个列表。

更令人困惑的是,如果我尝试对项目进行编码:

dict["Author"].encode('utf-8')

它说的是“列表对象没有方法,decode()”

这绝对是一个列表......那么为什么我会收到这个错误?

我正在使用 python 2.7

编辑:

所以这个例子是我实际处理的简化版本。 我使用scrapy抓取了一个网站,并返回了一个json文件。 解码后的 json 文件是一个包含字典的列表,其中包含更多列表。

项目.json:

[{"Title": ["Harry Potter"], "Author": ["J.K.Rowling"]}, 
 {"Title": ["Lord of the Rings"], "Author": ["J.R.R. Tolkien"]}]

我的代码:

import json
import csv


with open('items.json', 'r') as f:
    op = f.read()
    json = json.loads(op)


with open("data.csv", "wb") as f:
    csvWriter = csv.writer(f)
    csvWriter.writerow(['title', 'author'])

    for dic in json:
        title = dic['Title'][0]
        author = dic['Author'][0]

        csvWriter.writerow([title, author])

当我运行这段代码时,我得到了 IndexError

cscWriter.writerow 的参数应该是一个列表列表。 https://docs.python.org/2/library/csv.html如果要编码,请使用:dict["Author"][0].encode('utf-8')

想通了这个问题。

埋在我的 json 文件中的是空列表。 一开始我没有看到它们,但是我的程序找到了它们。 这个问题解决了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM