如何将列表的字典写成字符串而不是CSV文件? [英] How to write a dictionary of lists to a string instead of CSV file?
问题描述
此 stackoverflow问题将列表字典写入CSV文件的答案.我的用例是将类似的列表字典写入CSV字符串而不是文件中.如果我遵循
This stackoverflow question answers to write a dictionary of lists into a CSV file. My use case is to write a similar dictionary of lists into a CSV string instead of a file. If I do following
csvfile += ",".join(csvdata.keys())
for values in csvdata.values():
csvfile += ",".join(value for value in values) + "\n"
这给了我所有扩展到不同行的列表.取而代之的是,我正在寻找带有字典键作为列标题并且键的值(在列表中)与其列值相同的输出.
It is giving me all lists expanded in different rows. Instead, I am looking for an output with dictionary key as a column header and same key's values (in the list) as its column values.
Input
{'ID' :['101','102'], 'Name': ['X','Y'],'Gender': ['M','F']}
Expected Output (In comma separated string)
ID, Name, Gender
101, X, 'M'
102, Y, 'F'
Output with my code
ID, Name, Gender
101, 102,
X, Y,
'M', 'F',
编辑#1:在此处解释重复的请求.问题" 我如何将数据以字符串(而不是文件)的格式写入csv格式? "是针对另一种用例,我的问题是针对特定的用例.
Edit #1 : Explaining the duplicate request here. Question "How do I write data into csv format as string (not file)?" is for a different use-case, my question is rather for a specific one.
推荐答案
csvdata.values()
中的每个values
是其对应的键/列的值的列表,因此您可以有效地将表的列打印为行.
Each of the values
in csvdata.values()
is a list of values for its corresponding key / column, so you are effectively printing the columns of the table as rows.
相反,通过zip
值列表来构造行:
Instead, construct the rows by zip
ing the value lists:
csvfile += ",".join(csvdata.keys()) + "\n"
for row in zip(*csvdata.values()):
csvfile += ",".join(row) + "\n"
输出:
ID,Name,Gender
101,X,M
102,Y,F
这篇关于如何将列表的字典写成字符串而不是CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!