Skip to content Skip to sidebar Skip to footer

Make Dicts Read From A Csv File Ordered Dicts

When using csv.DictReader to read a csv file into a list of dictionaries, how can I make each dictionary an ordered dictionary ordered in the same order in the csv file? Thanks. im

Solution 1:

Use an OrderedDict with csv.reader:

from collections import OrderedDict
with open("in.csv") as csvfile:
    reader = csv.reader(csvfile,delimiter=" ")
    keys = next(reader)
    print([OrderedDict(zip(keys,row)) for row in reader ])


[OrderedDict([('first_name', 'Baked'), ('last_name', 'Beans')]), OrderedDict([('first_name', 'Lovely'), ('last_name', 'Spam')]), OrderedDict([('first_name', 'Wonderful'), ('last_name', 'Spam')])]

Or combine the two:

from collections import OrderedDict

withopen("in.csv") as csvfile:
    reader = csv.DictReader(csvfile,delimiter=" ")
    keys = reader.fieldnames
    r = csv.reader(csvfile,delimiter=" ")
    print([OrderedDict(zip(keys, row)) for row in r])

Solution 2:

Dictionaries are never ordered.

But, you can make a list of the keys of the dictionary in any order you want. Instead of iterating over the dictionary in its random order, iterate over your list of keys, and get each item from the dictionary by its key.

Where does the list of keys come from? You can specify it in the constructor of your DictReader object (see the docs), or you can use the fieldnames attribute that's set when you read the first row.

Post a Comment for "Make Dicts Read From A Csv File Ordered Dicts"