Python program to convert Dict of list to CSV
Last Updated :
28 Nov, 2021
Given a dictionary of list d, the task is to write a Python program to write a dictionary into a CSV file.
The idea to solve this problem is to zip the dictionary and then write it into a CSV file. Python provides an in-built module called ‘csv’ for working with CSV files. csv.writer class is used to write into CSV file. csv.writer class provide two methods for writing into csv file.
- writerow(): writerow() method is used to write single row.
- writerows(): writerows() method is used to write multiple rows.
Python3
import csv
d = { "key1" : [ 'a' , 'b' , 'c' ],
"key2" : [ 'd' , 'e' , 'f' ],
"key3" : [ 'g' , 'h' , 'i' ]}
with open ( "test.csv" , "w" ) as outfile:
writerfile = csv.writer(outfile)
writerfile.writerow(d.keys())
writerfile.writerows( zip ( * d.values()))
|
Output:
Python’s zip() function takes iterable as input and returns an iterator object. This iterator generates a series of tuples with each tuple having elements from each of the iterable.
Here lists in the dictionary are provided as input to the zip() and it will return a series of tuples with each tuple having elements from all lists these tuples will be treated as rows for CSV file.
Example:
Python3
import csv
d = { "key1" : [ 'a' , 'b' , 'c' ],
"key2" : [ 'd' , 'e' , 'f' ],
"key3" : [ 'g' , 'h' , 'i' ]}
with open ( "test.csv" , "w" ) as outfile:
writerfile = csv.writer(outfile)
writerfile.writerow(d.keys())
writerfile.writerows( zip ( * d.values()))
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...