简体   繁体   English

如何将 output 字典以 csv 格式输出到 python 中?

[英]How to output a dictionary to stdout in csv format in python?

I have been looking for ways to outputting a dictionary to standard output in a csv format.我一直在寻找以 csv 格式将字典输出为标准 output 的方法。

Dictionary has the following format字典具有以下格式

my_dict = {
  "column1": ["row1","row2","row3",...],
  "column2": ["row1","row2","row3",...],
  "column3": ["row1","row2","row3",...]
}

I have found solutions for outputting a dictionary to stdout:我找到了将字典输出到标准输出的解决方案:

Python: List of dictionaries: How to - nice printout using sys.stdout Python:词典列表:如何 - 使用 sys.stdout 进行漂亮的打印输出

I can always just sys.stdout every column and row in a for loop.我总是可以在 for 循环中只sys.stdout的每一列和每一行。 However, I am not confident about what will happen in the edge cases (which some library will do).但是,我不确定在边缘情况下会发生什么(某些图书馆会这样做)。

I have also found solutions for outputting a dictionary to csv: How do I write a Python dictionary to a csv file?我还找到了将字典输出到 csv 的解决方案: How do I write a Python dictionary to a csv file?

However, these always write the dictionary to a file object instead of stdout.但是,这些总是将字典写入文件 object 而不是标准输出。

My question is is there any way of outputting dictionaries to stdout in a csv format (that also handles edge cases such as: row values with , and " characters which will corrupt a csv file)?我的问题是有没有办法以 csv 格式将字典输出到 stdout(也处理边缘情况,例如:带有,"字符的行值会损坏 csv 文件)?

You can always use StringIO for methods that require a file-like object .您始终可以将 StringIO 用于需要类似文件StringIO的方法。 Also DictWriter is not the right tool for this task as it works on a list of dict s:此外DictWriter不是完成此任务的正确工具,因为它适用于dict list

import csv
from io import StringIO

my_dict = {
  "column1": ["row1", "row2", "row3",],
  "column2": ["row1", "row2", "row3",],
  "column3": ["row1", "row2", "row3",]
}

f = StringIO()
writer = csv.writer(f)
writer.writerow(my_dict.keys())
writer.writerows(zip(*my_dict.values()))

print(f.getvalue())

this would print这将打印

column1,column2,column3
row1,row1,row1
row2,row2,row2
row3,row3,row3

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

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