Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python read csv file with row and column headers into dictionary with two keys

I have csv file of the following format,

,col1,col2,col3
row1,23,42,77
row2,25,39,87
row3,48,67,53
row4,14,48,66

I need to read this into a dictionary of two keys such that

dict1['row1']['col2'] = 42
dict1['row4']['col3'] = 66

If I try to use csv.DictReader with default options

with open(filePath, "rb" ) as theFile:
    reader = csv.DictReader(theFile, delimiter=',')
    for line in reader:
    print line

I get the following output

{'': 'row1', 'col2': '42', 'col3': '77', 'col1': '23'}
{'': 'row2', 'col2': '39', 'col3': '87', 'col1': '25'}
{'': 'row3', 'col2': '67', 'col3': '53', 'col1': '48'}
{'': 'row4', 'col2': '48', 'col3': '66', 'col1': '14'}

I'm not sure of how to process this output to create the type of dictionary that I'm interested in.

For sake of completeness, it would also help if you can address how to write back the dictionary into a csv file with the above format

like image 907
rambalachandran Avatar asked Mar 06 '16 16:03

rambalachandran


1 Answers

Using the CSV module:

import csv
dict1 = {}

with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    headers = next(reader)[1:]
    for row in reader:
        dict1[row[0]] = {key: int(value) for key, value in zip(headers, row[1:])}
like image 196
Tim Pietzcker Avatar answered Sep 30 '22 18:09

Tim Pietzcker