简体   繁体   中英

How to write a dictionary of lists to a string instead of CSV file?

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',

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.

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.

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"

Output:

ID,Name,Gender
101,X,M
102,Y,F

Instead of performing manipulations with strings (joining them with commas and linebreaks) I suggest a more idiomatic and cleaner approach using a csv module and io.String :

import csv
import io


data = {'ID': ['101', '102'], 'Name': ['X', 'Y'], 'Gender': ['M', 'F']}

with io.StringIO() as output:
    writer = csv.writer(output)
    writer.writerow(data.keys())
    writer.writerows(zip(*data.values()))
    result = output.getvalue()
print(result)

This gives:

ID,Name,Gender
101,X,M
102,Y,F


References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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