How to automatically parse csv in python 2.7 into int, string and list objects and their values
Question: I want to be able to parse csv files that will be maintained outside of our
software group. A sample csv may contain:

    
    
    temperature,50,55,56
    color,blue
    count,10
    dummy,line
    

The code will search the file for a list of ints called temperature, a string
called color and an int called count. Then it will assign the values [50, 55,
56], 'blue' and 10 respectively.

  * The row ordering in the csv files is arbitrary (e.g. sometimes 'color' could come before 'temperature').
  * The object names are predefined but the values will vary between csv files.
  * The csv files will always contain the object names that the python code searches for.
  * The csv files may contain extra data rows that are not useful to the python code.
  * The object names will always be in the first column of the csv.

I have seen other code examples that search for specific object types, or
objects in predefined row positions. However, I need a solution that is more
robust.

Any help will be appreciated. Please let me know if you need clarification and
I will edit.


Answer: All you need is something like the following:

    
    
    import csv
    
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
    
        dummy = []
        temperature = []
        color = ''
        count = 0
    
        for row in reader:
            try:
                if row[0] == 'temperature':
                    temperature = map(int, row[1:])
                elif row[0] == 'color':
                    color = row[1]
                elif row[0] == 'count':
                    count = int(row[1])
                else:
                    dummy.append(row)
    
            # for robustness, let's catch the case where a row
            # may be malformed or does not contain more than 1 column
            except IndexError:
                dummy.append(row)
    

