Python program to convert Dict of list to CSV
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.
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.