如何将字典导入到csv

时间:2019-08-24 18:44:58

标签: python csv dictionary

我必须将数据从字典导出到csv。词典包含列表。我试图这样做

with open("info.csv", 'w',newline='')as csvfile:
header = ['Club', 'Stadium']
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
writer.writerow(info)

但是结果是

 Club          Stadium
 ['Arsenal,    ['Emirates',
 'AFC', etc.]  'Villia park',etc.]

我想要这个

Club         Stadium
Arsenal      Emirates
AFC          Villia park

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以像这样完成自己想做的事情。

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

我经常使用pandas,基本上它是一个单行,但是对您的需求来说可能算是过高了。

import pandas as pd
df = pd.DataFrame(info).to_csv('info.csv', index=False)

如果通常不需要使用pandas,则最好使用内置的csv模块。