arjun gulyani
arjun gulyani

Reputation: 711

Original order of columns in csv not retained in unicodecsv.DictReader

I am trying read a CSV file into python 3 using unicodecsv library. Code follows :

with open('filename.csv', 'rb') as f: 
    reader = unicodecsv.DictReader(f)
    Student_Data = list(reader)

But the order of the columns in the CSV file is not retained when I output any element from the Student_Data. The output contains any random order of the columns. Is there anything wrong with the code? How do I fix this?

Upvotes: 0

Views: 231

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24279

As stated in csv.DictReader documentation, the DictReader object behaves like a dict - so it is not ordered.

You can obtain the list of the fieldnames with:

reader.fieldnames

But if you only want to obtain a list of the field values, in original order, you can just use a normal reader:

with open('filename.csv', 'rb') as f: 
    reader = unicodecsv.reader(f)
    for row in reader:
        Student_Data = row

Upvotes: 1

Related Questions