0

I have been looking for ways to outputting a dictionary to standard output in a csv format.

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

I can always just sys.stdout every column and row in a for loop. 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?

However, these always write the dictionary to a file object instead of stdout.

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)?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
pregenRobot
  • 147
  • 1
  • 13

1 Answers1

1

You can always use StringIO for methods that require a file-like object. Also DictWriter is not the right tool for this task as it works on a list of dicts:

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
Selcuk
  • 57,004
  • 12
  • 102
  • 110