Open In App

How to save a Python Dictionary to a CSV File?

Last Updated : 01 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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


Similar Reads

NumPy save() Method | Save Array to a File
The NumPy save() method is used to store the input array in a binary file with the 'npy extension' (.npy). Example: C/C++ Code import numpy as np a = np.arange(5) np.save('array_file', a) SyntaxSyntax: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Parameters: file: File or filename to which the data is saved. If the file is a string or
2 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Python - Save List to CSV
A CSV (Comma Separated Values) is a simple file format, used to store data in a tabular format. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file form
3 min read
Save image properties to CSV using Python
In this article, we are going to write python scripts to find the height, width, no. of channels in a given image file and save it into CSV format. Below is the implementation for the same using Python3. The prerequisite of this topic is that you have already installed NumPy and OpenCV. Approach: First, we will load the required libraries into the
3 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
Save a dictionary to a file
A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here. Syntax: dictionary = {'geek': 1, 'supergeek': True, 4: 'geek
2 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
Article Tags :
Practice Tags :