问题
I have to export data from dictionary to csv. Dictionary contains lists. I tried to do export like this
with open("info.csv", 'w',newline='')as csvfile:
header = ['Club', 'Stadium']
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
writer.writerow(info)
But the result is
Club Stadium
['Arsenal, ['Emirates',
'AFC', etc.] 'Villia park',etc.]
And i wanted this
Club Stadium
Arsenal Emirates
AFC Villia park
How can i do it?
回答1:
You can accomplish what you want doing it like this.
import csv
with open('info.csv', 'w', newline='') as f:
header = info.keys()
writer = csv.DictWriter(f, fieldnames=header)
writer.writeheader()
for pivoted in zip(*info.values()): # here we take both lists and pivot them
writer.writerow(dict(zip(header, pivoted))) # pivoted is a 2 element tuple
I often use pandas
and it's basically a oneliner with it, but it might be an overkill for your needs.
import pandas as pd
df = pd.DataFrame(info).to_csv('info.csv', index=False)
If you don't need to use pandas
in general, better stick with built-in csv
module.
来源:https://stackoverflow.com/questions/57640691/how-to-import-dictionary-to-csv