0

我想将 csv.reader 中的内容转换为字典。我实施了这篇文章中的说明 Add new keys to a dictionary?但我不断得到IndexError: list index out of range。我怎样才能解决这个问题?

import wx
import csv

info = csv.reader(open('report.csv', 'rb'),delimiter=',')

length = 0
info_list = []

for row in info: #search each row in the report
    info_list.append([length,row[1],row[4]])
    length = length + 1

print length
dict_info = {}
rows = 0
counter = 0

while counter < length:
    for item in info_list:
        dict_info[item[rows]] = [item[rows + 1], item[rows + 2]]
    rows = rows + 3
    counter = counter + 1
print dict_info
4

3 回答 3

0

导入集合

d = collections.OrderedDict()

info = csv.reader(open('report.csv', 'rb'),delimiter=',')

d = {row[0]:row[1].strip() for row in info}

对于 d.items() 中的 some1、some2:

而不是写其他所有东西

于 2013-06-28T16:04:31.780 回答
0
for index, row in enumerate(info):
    dict_info[index] = [row[1], row[4]]
于 2013-06-28T15:59:13.993 回答
0

我认为你想要做的是:

import csv

info = csv.reader(open('report.csv', 'rb'),delimiter=',')
dict_info = {row[0]:[row[1], row[4]] for row in info}
print dict_info

如果您希望索引是文件的行号,那么您可能应该将其保留为列表。

import csv

info = csv.reader(open('report.csv', 'rb'),delimiter=',')
list_info = [[row[1], row[4]] for row in info]
print list_info
于 2013-06-28T16:09:23.670 回答