从每个键具有多个值的字典将数据写入CSV [英] writing data to csv from dictionaries with multiple values per key

查看:247
本文介绍了从每个键具有多个值的字典将数据写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我将数据存储在字典中.词典的长度可以不同,并且在特定词典中,键可能具有多个值.我正在尝试将数据吐出到CSV文件中.

I am storing data in dictionaries. The dictionaries can be off different length and in a particular dictionary there could be keys with multiple values. I am trying to spit out the data on a CSV file.

问题/解决方案

图像1是我的实际输出打印出来的方式.图2显示了我希望我的输出实际打印出来的方式. 图像2是所需的输出.

Image 1 is how my actual output prints out. Image 2 shows how i would want my output to actually printout. Image 2 is the desired output.

代码

import csv
from itertools import izip_longest

e = {'Lebron':[25,10],'Ray':[40,15]}
c = {'Nba':5000}

def writeData():
    with open('file1.csv', mode='w') as csv_file:
        fieldnames = ['Player Name','Points','Assist','Company','Total Employes']
        writer = csv.writer(csv_file)
        writer.writerow(fieldnames)

        for employee, company in izip_longest(e.items(), c.items()):
            row = list(employee)
            row += list(company) if company is not None else ['', '']  # Write empty fields if no company

            writer.writerow(row)

writeData()

我愿意接受所有可以帮助我获得所需输出格式的解决方案/建议.

I am open to all solutions/suggestions that can help me get my desired output format.

推荐答案

要获得更简单的答案,您只需在所拥有的内容中添加一行代码即可.

For a much simpler answer, you just need to add one line of code to what you have:

row = [row[0]] + row[1]

如此:

for employee, company in izip_longest(e.items(), c.items()):
        row = list(employee)
        row = [row[0]] + row[1]
        row += list(company) if company is not None else ['', '']  # Write empty fields if no company

这篇关于从每个键具有多个值的字典将数据写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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