Parker Parker - 28 days ago 10
Python Question

Write dict to csv file with keys not in alphabetic order

I know that when using python to write dicts to csv files, the headers will be put in alphabetic order. So is there a way that I can write the header with the order I want?

The code and outputs of tsv file is below.

I have a dict:

my_data = {"name": name[:], "city": city[:], "state": state[:],
"stars": stars[:], "review_count": review_count[:],
"main_category": new_cat[:]}


And I used following code to write them in csv file:

with open('test.tsv','w') as file:
writer = csv.writer(file, delimiter='\t')
writer.writerow(my_data.keys())
for row in zip(*my_data.values()):
writer.writerow(list(row))


And the first several rows of the output of the tsv file is below:

city review_count name main_category state stars
Los Angeles 2 Southern California Medical Group Medical Centers CA 3.5
Cambridge 4 Harvard Square Shiatsu Massage MA 4.0
Kitchener 2 Faith & Glory Collective Tattoo ON 4.0


You can see that they are put in an alphabetic order, but what I really want is that they can be put in the order of keys in my_data like this:

name city state stars review_count main_category

Answer

The following will put things in the order you want:

import csv

# defines order of fields in output tsv file
ORDER = "name city state stars review_count main_category".split()

my_data = {"name": name[:], "city": city[:], "state": state[:],
           "stars": stars[:], "review_count": review_count[:],
           "main_category": new_cat[:]}

def sequence_data(my_data, order):
    for i in range(1, len(my_data[order[0]])):
        yield [my_data[key][i] for key in order]

with open('test.tsv','w') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerow(ORDER)
    for row in sequence_data(my_data, ORDER):
        writer.writerow(row)

This is the contents of the test.tsv file created (where » represents the tab delimiter characters):

name»city»state»stars»review_count»main_category
Southern California Medical Group»Los Angeles»CA»3.5»2»Medical Centers
Harvard Square Shiatsu»Cambridge»MA»4.0»4»Massage
Faith & Glory Collective»Kitchener»ON»4.0»2»Tattoo