Creating a dictionary from CSV using python

2020-06-30 00:09发布

问题:

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?

回答1:

The extra code you have is unnecessary. csv already does the heavy-lifting for you. Just use csv.DictReader as is:

import csv

with open('e.txt') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

The above outputs:

OrderedDict([('A', '1'), (' B', ' 4'), (' C', ' 7')])
OrderedDict([('A', '2'), (' B', ' 5'), (' C', ' 8')])
OrderedDict([('A', '3'), (' B', ' 6'), (' C', ' 9')])    

You may think you want a dict rather than an OrderedDict, but I'm fairly sure you don't. Using an OrderedDict object will ensure that your rows stay ordered correctly.

thank you for your reply. This seems to work but for my task, I need it in the format mentioned in the question. Is there a way to turn it into that format?

Why exactly? Don't be fooled by the format. OrderedDict behaves the exact same as a normally dictionary. The only difference is that OrderedDict will maintain its order. If all you need is to print your rows in a certain format, you can convert each row to a dict and use it's __repr__:

for row in reader:
    print(dict(row))