0

I want to build two very similar dictionaries from the same csv file (one mapping row[0] to row[5], one from row[0] to row[6]. For some reason, I can only build one. Whichever of these two lines I run first, the dictionary exists and does exactly what I want. The other is empty. No idea what's going wrong.

mydict = {row[0]:row[5] for row in csv.reader(g)}
mydict1 = {row[0]:row[6] for row in csv.reader(g)}

I am using python 3, and tried changing the dictionary name and a few other things.

Joe
  • 5
  • 3
  • 1
    uh, related: http://stackoverflow.com/questions/431752/python-csv-reader-how-do-i-return-to-the-top-of-the-file – NightShadeQueen Jul 14 '15 at 13:40
  • The tl;dr is "file objects in python are generators, you need to explicitly return to the top of the file or reopen it, see the link" – NightShadeQueen Jul 14 '15 at 13:41
  • The problem is that once you've iterated over the first `reader`, you've **reached the end of the file**, and need to rewind or reopen it. – jonrsharpe Jul 14 '15 at 13:41

1 Answers1

3

You cannot iterate over a file twice without rewinding it to the start. Doing so is not very efficient either; better to not use dictionary comprehensions here:

mydict1, mydict2 = {}, {}
for row in csv.reader(g):
    mydict1[row[0]] = row[5]
    mydict2[row[0]] = row[6]

If you really insist, you can use a file.seek(0) to put the file pointer back to the start; you don't need to re-create the reader here:

reader = csv.reader(g)
mydict1 = {row[0]:row[5] for row in reader}
g.seek(0)
mydict2 = {row[0]:row[6] for row in reader}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343