1

I am attempting to convert a csv file into a python data dictionary.

Here my code:

import csv
picset = Set_1
with open('/Users/vp_enc_' + str(picset) + '_eeg_trigger_codes.csv', mode='r') as f:
    reader = csv.reader(f)
    triggerdict = dict((rows[0],{'code': rows[1], 'letter': rows[2], 'marker': rows[3], 'r': rows[4], 'g': rows[5], 'b': rows[6]}) for rows in reader)

Here are what initial rows of the csv file look like:

code,letter,marker,r,g,b
107Neg1,A,151,84,4,1
1Neg1,A,152,0,5,1
6Neg1,A,153,4,5,1
7Neg1,A,154,16,5,1
10Neg1,A,155,20,5,1
12Neg1,A,156,64,5,1
13Neg1,A,157,68,5,1
17Neg1,A,158,80,5,1
21Neg1,A,159,84,5,1
22Neg1,A,160,0,16,1
24Neg1,A,161,4,16,1
25Neg1,A,162,16,16,1
28Neg1,A,163,20,16,1
30Neg1,A,164,64,16,1
31Neg1,A,165,68,16,1
34Neg1,A,166,80,16,1
35Neg1,A,167,84,16,1
36Neg1,A,168,0,17,1
41Neg1,A,169,4,17,1
47Neg1,A,170,16,17,1
50Neg1,A,171,20,17,1
51Neg1,A,172,64,17,1
53Neg1,A,173,68,17,1
58Neg1,A,174,80,17,1
62Neg1,A,175,84,17,1

This works:

with open('/Users/vp_enc_' + str(picset) + '_eeg_trigger_codes.csv', mode='r') as f:
    reader = csv.reader(f)
    triggerdict = dict((rows[0],{'code': rows[1], 'letter': rows[2], 'marker': rows[3], 'r': rows[4]}) for rows in reader)

But when I include rows 5 and 6, it give me this error:

Traceback (most recent call last):
  File "<input>", line 3, in <module>
  File "<input>", line 3, in <genexpr>
IndexError: list index out of range

Tried to troubleshoot, but unclear why there is an error.

arkadiy
  • 746
  • 1
  • 10
  • 26
  • try printing out the `row` and see what you get. That should tell you why `row[5]` or `row[6]` is giving you an `list index out of range` error – whiplash Dec 15 '21 at 17:08

1 Answers1

1

Your csv file has 6 columns and rows[6] is trying to access the value of the 7th column because indexes start at zero. So, because the 7th element does not exist, it raises IndexError: list index out of range error.

Mustafa Shujaie
  • 1,447
  • 1
  • 16
  • 30
  • When I correct it as you suggested (below), the same error persists triggerdict = dict((rows[0],{'letter': rows[1], 'marker': rows[2], 'r': rows[3], 'b': rows[4], 'g': rows[5]}) for rows in reader) – arkadiy Dec 15 '21 at 17:19
  • @arkadiy I checked it with the CSV data in your question and it works. Check the CSV file that you are working with and make sure all rows have 6 columns. – Mustafa Shujaie Dec 15 '21 at 17:24