Saturday, August 30, 2025
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

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7012 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS