简体   繁体   English

从多个字典写入单个 CSV 文件

[英]writing to a single CSV file from multiple dictionaries

Background背景

I have multiple dictionaries of different lengths.我有多个不同长度的字典。 I need to write the values of dictionaries to a single CSV file.我需要将字典的值写入单个 CSV 文件。 I figured I can loop through each dictionary one by one and write the data to CSV.我想我可以一个一个地遍历每个字典并将数据写入 CSV。 I ran in to a small formatting issue.我遇到了一个小的格式问题。

Problem/Solution问题方案

I realized after I loop through the first dictionary the data of the second writing gets written the row where the first dictionary ended as displayed in the first image I would ideally want my data to print as show in the second image我意识到在我遍历第一个字典后,第二个写作的数据被写入第一个字典结束的行,如第一张图像所示我理想地希望我的数据打印如第二张图像所示

在此处输入图片说明 在此处输入图片说明

My Code我的代码

import csv

    e = {'Jay':10,'Ray':40}
    c = {'Google':5000}

    def writeData():
        with open('employee_file20.csv', mode='w') as csv_file:
            fieldnames = ['emp_name','age','company_name','size']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()

            for name in e:
                 writer.writerow({'emp_name':name,'age':e.get(name)})

            for company in c:
                writer.writerow({'company_name':company,'size':c.get(company)})


    writeData()

PS: I would have more than 2 dictionaries so I am looking for a generic way where I can print data from row under the header for all the dictionaries. PS:我会有 2 个以上的字典,所以我正在寻找一种通用的方式,我可以从所有字典的标题下的行打印数据。 I am open to all solutions and suggestions.我对所有解决方案和建议持开放态度。

If all dictionaries are of equal size, you could use zip to iterate over them in parallel.如果所有字典的大小相同,您可以使用zip并行迭代它们。 If they aren't of equal size, and you want the iteration to pad to the longest dict, you could use itertools.zip_longest如果它们的大小不同,并且您希望迭代填充到最长的字典,则可以使用itertools.zip_longest

For example:例如:

import csv
from itertools import zip_longest

e = {'Jay':10,'Ray':40}
c = {'Google':5000}

def writeData():
    with open('employee_file20.csv', mode='w') as csv_file:
        fieldnames = ['emp_name','age','company_name','size']
        writer = csv.writer(csv_file)
        writer.writerow(fieldnames)

        for employee, company in zip_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()

If the dicts are of equal size, it's simpler:如果字典大小相同,则更简单:

import csv

e = {'Jay':10,'Ray':40}
c = {'Google':5000, 'Yahoo': 3000}

def writeData():
    with open('employee_file20.csv', mode='w') as csv_file:
        fieldnames = ['emp_name', 'age', 'company_name', 'size']
        writer = csv.writer(csv_file)
        writer.writerow(fieldnames)

        for employee, company in zip(e.items(), c.items()):
            writer.writerow(employee + company)

writeData()

A little side note: If you use Python3, dictionaries are ordered.一个小小的旁注:如果你使用 Python3,字典是有序的。 This isn't the case in Python2.在 Python2 中不是这种情况。 So if you use Python2, you should use collections.OrderedDict instead of the standard dictionary.所以如果你使用 Python2,你应该使用collections.OrderedDict而不是标准字典。

There might be a more pythonic solution, but I'd do something like this:可能有更pythonic的解决方案,但我会做这样的事情:

I haven't used your .csv writer thing before, so I just made my own comma separated output.我之前没有使用过你的 .csv writer,所以我只是制作了自己的逗号分隔输出。

e = {'Jay':10,'Ray':40}
c = {'Google':5000}
dict_list = [e,c] # add more dicts here.
max_dict_size = max(len(d) for d in dict_list)
output = ""
# Add header information here.
for i in range(max_dict_size):
  for j in range(len(dict_list)):
    key, value = dict_list[j].popitem() if len(dict_list[j]) else ("","")
    output += f"{key},{value},"
  output += "\n"
# Now output should contain the full text of the .csv file
# Do file manipulation here.
# You could also do it after each row,
# Where I currently have the output += "\n"

Edit: A little more thinking and I found something that might polish this a bit.编辑:多一点思考,我发现了一些可能会改善这一点的东西。 You could first map the dictionary into a list of keys using the .key() function on each dictionary and appending those to an empty list.您可以首先使用每个字典上的 .key() 函数将字典映射到一个键列表中,并将它们附加到一个空列表中。

The advantage with that is that you'd be able to go "forward" instead of popping the dictionary items off the back.这样做的好处是你可以“前进”而不是从后面弹出字典项目。 It also wouldn't destroy the dictionary.它也不会破坏字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM