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