Sunday, July 5, 2026
HomeLanguagesHow to save a Python Dictionary to a CSV File?

How to save a Python Dictionary to a CSV File?

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.
  5. 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

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12015 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7263 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6967 POSTS0 COMMENTS