Creating a dictionary from CSV using python

前端 未结 1 871
谎友^
谎友^ 2021-01-03 16:54

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

<
相关标签:
1条回答
  • 2021-01-03 17:15

    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))
    
    0 讨论(0)
提交回复
热议问题