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
# Program to write a dictionary of list to csv import csv # dictionary of list d = { "key1" : [ 'a' , 'b' , 'c' ], "key2" : [ 'd' , 'e' , 'f' ], "key3" : [ 'g' , 'h' , 'i' ]} # writing to csv file with open ( "test.csv" , "w" ) as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary 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
# Program to write a dictionary of list to csv import csv # dictionary of list d = { "key1" : [ 'a' , 'b' , 'c' ], "key2" : [ 'd' , 'e' , 'f' ], "key3" : [ 'g' , 'h' , 'i' ]} # writing to csv file with open ( "test.csv" , "w" ) as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary writerfile.writerows( zip ( * d.values())) |
Output: