Menu

Writing to a CSV file - fields in wrong order - help me understand why

Reading 0:00
15s threshold

I developed a process that writes data to a CSV file using csv.DictWriter. The consumer of this file requires that the fields are in a specific order. However, the fields were coming out in the wrong order (different than the order in the dictionary).

Here is the code that worked incorrectly:

writer = csv.DictWriter(csfvile, fieldname=data[0].keys())

Note: data is a list of dictionaries.

The fix is to add a list comprehension around the data[0].keys(). Here is the code that works correctly:

writer = csv.DictWriter(csfvile, fieldname=[key for key indata[0].keys()])

Can anyone explain why the csv.DictWritemodule punches out fields in a different order in the first version?

submitted by /u/Amo-Rillow
[link] [comments]