I have a CSV of the format
where A, B & C are the headers.
How do I pythonically convert this CSV into a dictionary of the following form
{'A': '1', 'B': '4','C': '7'},
{'A': '2', 'B': '5','C': '8'},
{'A': '3', 'B': '6','C': '9'}
So far I'm trying the following code:
import csv
reader = csv.DictReader(open('file.csv'))
result = {}
for row in reader:
for column, value in row.items():
result.setdefault(column, []).append(value)
This is not giving me the intended output. Any suggestions?
The extra code you have is unnecessary.
csv
already does the heavy-lifting for you. Just usecsv.DictReader
as is:The above outputs:
You may think you want a
dict
rather than anOrderedDict
, but I'm fairly sure you don't. Using anOrderedDict
object will ensure that your rows stay ordered correctly.Why exactly? Don't be fooled by the format.
OrderedDict
behaves the exact same as a normally dictionary. The only difference is thatOrderedDict
will maintain its order. If all you need is to print your rows in a certain format, you can convert each row to adict
and use it's__repr__
: