For example, my csv has columns as below:
ID, ID2, Date, Job No, Code
I need to write the columns back in the same order. The dict jumbles the order immediately, so I believe it’s more of a problem with the reader.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python’s
dicts do NOT maintain order prior to 3.6 (but, regardless, in that version thecsv.DictReaderclass was modified to returnOrderedDicts).However, the instance of
csv.DictReaderthat you’re using (after you’ve read the first row!-) does have a.fieldnameslist of strings, which IS in order.So,
will show you that the order is indeed maintained (in
.fieldnamesof course, NEVER in thedict— that’s intrinsically impossible in Python!-).So, suppose you want to read
a.csvand writeb.csvwith the same column order. Using plain reader and writer is too easy, so you want to use the Dict varieties instead;-). Well, one way is…:assuming you have headers in
a.csv(otherewise you can’t use a DictReader on it) and want just the same headers inb.csv.