Reputation: 3205
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.
Upvotes: 3
Views: 248
Reputation: 13717
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:
Upvotes: 0
Reputation: 15035
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
Upvotes: 4