How to extract certain csv data based on the header in python

csv, python

Solution

I second the `csv` recommendation, but I think here using `csv.DictReader` would be simpler:

(Python 2):

>>> import csv
>>> with open("hwa.csv", "rb") as fp:
...     reader = csv.DictReader(fp)
...     data = next(reader)
...     
>>> data
{'Age': '25', 'Weight': '78', 'Height': '6.0'}
>>> data["Age"]
'25'
>>> float(data["Age"])
25.0

Here I've used `next` just to get the first row, but you could loop over the rows and/or extract a full column of information if you liked.

Problem

How would I extract specific data from a csv file, based on the header in python? For example, say the csv file contained this information: ``` Height,Weight,Age 6.0,78,25 ``` How could I retrieve just the age in python?

Original source