Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a dictionary of lists to csv in Python [duplicate]

I have a dictionary like {a: [1, 2, 3], b: [4, 5, 6], c: [7, 3, 2]} and I would like to write this to a csv file in Python. I was the csv file as:

col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2

I tried using CSV Dict writer but I could not get as value is a list here.

Any help is appreciated!

like image 643
Cool Geek Avatar asked Mar 23 '16 18:03

Cool Geek


1 Answers

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:
like image 149
Martin Evans Avatar answered Sep 28 '22 08:09

Martin Evans