Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to save a Python Dictionary to a CSV File?

  • Last Updated : 01 Jul, 2020

Prerequisites: Working with csv files in Python

CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same.

  1. Import csv module
    import csv
  2. Creating list of field names
    field_names= ['No', 'Company', 'Car Model']
  3. Creating a list of python dictionaries

    cars = [
    {‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},
    {‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},
    {‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},
    {‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},
    {‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},
    ]

  4. Writing content of dictionaries to CSV file
    with open('Names.csv', 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=field_names)
        writer.writeheader()
        writer.writerows(cars)

    Syntax:

    DictWriter( (filename), fieldnames = [list of field names] )

    In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:

    1. DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV file
    2. csvwriter.writerows() method is used to write rows of data into the specified file.

    Note: To write a single dictionary in CSV file use writerow() method

Complete code to write python dictionaries in CSV file




import csv
  
field_names = ['No', 'Company', 'Car Model']
  
cars = [
{'No': 1, 'Company': 'Ferrari', 'Car Model': '488 GTB'},
{'No': 2, 'Company': 'Porsche', 'Car Model': '918 Spyder'},
{'No': 3, 'Company': 'Bugatti', 'Car Model': 'La Voiture Noire'},
{'No': 4, 'Company': 'Rolls Royce', 'Car Model': 'Phantom'},
{'No': 5, 'Company': 'BMW', 'Car Model': 'BMW X7'},
]
  
with open('Names.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = field_names)
    writer.writeheader()
    writer.writerows(cars)

Output:

python-dictionary-to-csv

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!