Wednesday, 15 January 2014

Python writing a csv to dictionary with headers as keys and rows as values -



Python writing a csv to dictionary with headers as keys and rows as values -

i have csv file, test.csv, shown:

1,2,3 a,b,c d,e,f

i want above dictionary shown:

{"1":"a", "2":"b", "3":"c"} {"1":"d", "2":"e", "3":"f"}

where header 1,2,3 keys , rows values.

i don't quite understand how done using csv.dictreader. above sample that, sample. actual info i'm working has many columns, , hence, cannot access each row using index , manually putting them dictionary.

answering own question. after trying sometime played around bit more , added loop.

with open("test.csv") f: records = csv.dictreader(f) row in records: print row

this gives desired output of

{'1': 'a', '3': 'c', '2': 'b'} {'1': 'd', '3': 'f', '2': 'e'}

python csv dictionary

No comments:

Post a Comment