Python Dict from CSV IndexError
Question: I need to compare 2 CSV files and I am trying to use the @Martijn Pieters
solution at [Python: Comparing two CSV files and searching for similar
items](http://stackoverflow.com/questions/5268929/python-comparing-two-csv-
files-and-searching-for-similar-items) but I am running into an error:

    
    
    IndexError: list index out of range
    

Here is the code I am using,

    
    
    import csv
    with open('filename.csv', 'rb') as a:
      indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
      print indices
    

filename.csv has 10 columns and 2000 rows. I want to index column 3 that has
hostnames and then match with hostnames in other .csv file

    
    
    type,id,hostname,os,,,,
    phy,123,server1,rhel5,,,,
    vir,234,server2,rhel6,,,,
    

I am not sure why I am getting IndexError. Please help to fix the problem.


Answer: You probably have empty lines at the start or end of your csv file.

I was able to reproduce this error with the following code:

    
    
    import csv
    
    with open('filename.csv', 'wb') as a:
        strng = """
    type,id,hostname,os,,,,
    phy,123,server1,rhel5,,,,
    vir,234,server2,rhel6,,,,
    
    """
        a.write(strng)
    
    with open('filename.csv', 'rb') as a:
        indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
        print indices
    

However when I removed those blank lines, the code runs perfectly :

    
    
    import csv
    
    with open('filename.csv', 'wb') as a:
        strng = """type,id,hostname,os,,,,
    phy,123,server1,rhel5,,,,
    vir,234,server2,rhel6,,,,    
    """
        a.write(strng)
    
    with open('filename.csv', 'rb') as a:
        indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
        print indices
    

Refer to this [SO Answer](http://stackoverflow.com/a/18891114/3244627) on how
to skip blank lines in csv.

