You can use Python's csv
library for doing this as follows (for Python 3.x see below):
import csv
my_dict = {"a" : [1, 2, 3], "b" : [4, 5, 6], "c" : [7, 3, 2]}
with open("output.csv", "wb") as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(['col1', 'col2', 'col3', 'col4'])
for key in sorted(my_dict.keys()):
csv_output.writerow([key] + my_dict[key])
Giving you:
col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2
The .writerow()
function takes a list of items and writes them correctly formatted to your output CSV file. As you want the key as the first item, it passes the key
concatenated with them items found when looking the key
up in the my_dict
dictionary, thus resulting in the output that you wanted.
Note: If Python 3.x is used, the file open line would need to be modified, and sorting would not be required:
with open("output.csv", "w", newline="") as f_output: