如何将字典导入到csv [英] How to import dictionary to csv

查看:81
本文介绍了如何将字典导入到csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

但是结果是

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

我想要这个

Club         Stadium
Arsenal      Emirates
AFC          Villia park

我该怎么办?

推荐答案

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

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

我经常使用 pandas ,它基本上是一个单一的选择,但是对于您的需求来说可能是一个过大的选择.

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)

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

If you don't need to use pandas in general, better stick with built-in csv module.

这篇关于如何将字典导入到csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆