0

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?

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
arjun gulyani
  • 669
  • 2
  • 8
  • 23
  • 1
    This might help: https://stackoverflow.com/questions/1885324/is-it-possible-to-keep-the-column-order-using-the-python-csv-dictreader – fenceop Jul 03 '17 at 19:13

1 Answers1

1

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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50