How to import dictionary to csv

丶灬走出姿态 提交于 2021-01-27 13:26:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!