How to Convert Python Dictionary to CSV File

To convert a dictionary to csv in Python, you can use the “csv.DictWriter()” method. The DictWriter() method creates an object which operates like the regular writer but maps the dictionaries onto output rows.


import csv

dict = {'name': 'krunal', 'age': 26, 'education': 'Engineering'}

with open('data.csv', 'w') as f:
  for key in dict.keys():
    f.write("%s, %s\n" % (key, dict[key]))


name, krunal
age, 26
education, Engineering

The CSV module contains the DictWriter() method that requires the name of the CSV file to write and a list object containing field names.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.