如何将字典导入cs

2024-09-28 22:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须将数据从字典导出到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

我该怎么做?你知道吗


Tags: csv数据csvfileinfopark字典etcwriter
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:48

你可以这样做来完成你想做的事。你知道吗

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模块。你知道吗

相关问题 更多 >