python - How to create dict using csv file with first row as keys -


i'd create list of dictionaries reading large csv file uses entries first row keys. example, test.csv

header1, header2, header3 a,       1,       10 b,       2,       20 c,       3,       30 

the resulting dict like:

mylist = [{'header1': a, 'header2': 1, 'header3: 10}, {'header1': b,     'header2': 2, 'header3: 20}, {'header1': c, 'header2': 3, 'header3: 30}] 

i know how read file, , think maybe defaultdict collections might way, can't syntax right.

this csv.dictreader made for.

import csv  open('data.csv') f:     reader = csv.dictreader(f)     row in reader:         print row 

for data.csv containing:

header1,header2,header3 a,1,10 b,2,20 c,3,30 

it prints:

{'header2': '1', 'header3': '10', 'header1': 'a'} {'header2': '2', 'header3': '20', 'header1': 'b'} {'header2': '3', 'header3': '30', 'header1': 'c'} 

Comments

Popular posts from this blog

How to group boxplot outliers in gnuplot -

cakephp - simple blog with croogo -