0

I would like to convert stuff from my csv.reader to a dictionary. I implemented the instructions from this post Add new keys to a dictionary? but I keep getting IndexError: list index out of range. How can I fix this?

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
Community
  • 1
  • 1
1vko
  • 81
  • 6
  • Could you explain what you're trying to achieve in a paragraph? – Jon Clements Jun 28 '13 at 15:56
  • 3
    You are overrunning the bounds of the second `item` you iterate over, which is a list, because each iteration of the `while` loop adds 3 to the `row` value you are indexing in to `item` with, but `item` is only 3 elements long (since you created it as such while looping through `info`). You're getting an index error on the list; the dict isn't having a problem. I second @JonClements though in wanting to know what you are actually trying to do. – Silas Ray Jun 28 '13 at 15:59

3 Answers3

0
for index, row in enumerate(info):
    dict_info[index] = [row[1], row[4]]
a-b-r-o-w-n
  • 515
  • 2
  • 17
0

import collections

d = collections.OrderedDict()

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

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

for some1, some2 in d.items():

and than write everything else

0

I think what you are trying to do is:

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

If you want the indexes to be the line number if the file, then you should probably just keep it as a list.

import csv

info = csv.reader(open('report.csv', 'rb'),delimiter=',')
list_info = [[row[1], row[4]] for row in info]
print list_info
Silas Ray
  • 25,682
  • 5
  • 48
  • 63