Python read csv into dictionary rows

Read a csv with headers in python into dictionary rows mapping to the headers.


Use csv.DictReader to read each row into a dictionary.

import csv
with open('data.csv') as f:
    reader = csv.DictReader(f)
    print('headers: {}'.format(reader.fieldnames))
    for row in reader:
$ python 
headers found: ['first', 'last', 'sex']
{'sex': 'female', 'last': 'Mariana', 'first': 'Liberia'}
{'sex': 'male', 'last': 'Prosperus', 'first': 'Eligius'}
{'sex': 'female', 'last': 'Xenia', 'first': 'Florina'}

Alternatively, use csv.reader to read the rows.

import csv
with open('data.csv') as f:
    reader = csv.reader(f)
    headers =
    print('headers found: {}'.format(headers))
    for row_list in reader:
        row_dict = dict(zip(headers, row_list))

You can also read the next line by doing either or next(reader):

headers =
headers = next(reader)
Did this help you? Please let me know with a comment. Thank you
Posted .

Comments (RSS)

Leave a comment