Write a Dictionary to a CSV file in Python

In this article, we will discuss different ways to add a dictionary to a csv file as a row, in Python.

Table Of Contents

Write a Dictionary to a CSV file using DictWriter

Suppose we have few dictionaries,

row1 = {'Name' : 'Ritika', 'Age' : 27, 'City' : 'Delhi',     'Country' : 'India'}
row2 = {'Name' : 'Mark',   'Age' : 28, 'City' : 'Sydney',    'Country' : 'India'}
row3 = {'Name' : 'Suse',   'Age' : 29, 'City' : 'Las Vegas', 'Country' : 'India'}
row4 = {'Name' : 'Shaun',  'Age' : 30, 'City' : 'London',    'Country' : 'India'}

We want to add each of these dictionaries as a separate row in the csv file. Our csv file should be like this,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,India
Suse,29,Las Vegas,India
Shaun,30,London,India

Let’s see how to do that.

Open the file in write mode, and get a file object. Pass the file object to DictWriter() function of csv module to get the DictWriter object. With the help of this DictWriter object, we can write dictionaries to a csv file.

While creating a DictWriter object, pass a list of strings as column names. Strings in this list will be used as column names in the csv file. Then we call the writeheader() function of the DictWriter object to add the header in the csv file. Then call the writerow() function with either a single dictionary, or a list of dictionaries. It will add each dictionary as a row in the csv file.

Let’s see an example,

import csv

# Dictionaries, that need to be added into csv file as rows
row1 = {'Name' : 'Ritika', 'Age' : 27, 'City' : 'Delhi',     'Country' : 'India'}
row2 = {'Name' : 'Mark',   'Age' : 28, 'City' : 'Sydney',    'Country' : 'India'}
row3 = {'Name' : 'Suse',   'Age' : 29, 'City' : 'Las Vegas', 'Country' : 'India'}
row4 = {'Name' : 'Shaun',  'Age' : 30, 'City' : 'London',    'Country' : 'India'}

# Open file, and get file object
with open('employees.csv', 'w') as fileObject:
    # Create a DictWriter object with header
    writerObj = csv.DictWriter(fileObject, fieldnames = row1.keys())
    # Add header to the csv file
    writerObj.writeheader()
    # Add a dictionary as a row into the csv file
    writerObj.writerow(row1)
    # Add a dictionary as a row into the csv file
    writerObj.writerow(row2)
    # Add a list of dictionaries as rows into the csv file
    writerObj.writerows([row3, row4])

It will create a csv file with name employees.csv, and add the dictionaries into csv file as rows. Contents of the employees.csv will be,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,India
Suse,29,Las Vegas,India
Shaun,30,London,India

Write a Dictionary to a CSV file using Pandas

Suppose we a few dictionary,

mapping = { 'Name'    : ['Ritika', 'Mark', 'Suse', 'Shaun'],
            'Age'     : [27, 28, 29, 30],
            'City'    : ['Delhi', 'Sydney', 'Las Vegas', 'London'],
            'Country' : ['India', 'Australia', 'USA', 'UK']}

Now we want to add each key-value pair in this dictionary as a column in the csv file. While adding this dictionary into the csv file, for each item of the dictionary, key should be considered as column name, and corresponding value i.e. a list, should be considered as column values.

For this, first we will create a Pandas DataFrame object from this dictionary, and then call the to_csv() function of DataFrame to write it to the csv file.

Let’s see an example,

import pandas as pd

# Create a dictionary where each item contains
# a column for csv file
mapping = { 'Name'    : ['Ritika', 'Mark', 'Suse', 'Shaun'],
            'Age'     : [27, 28, 29, 30],
            'City'    : ['Delhi', 'Sydney', 'Las Vegas', 'London'],
            'Country' : ['India', 'Australia', 'USA', 'UK']}

# Create a DataFrame from mapping
df = pd.DataFrame(mapping)
df = df.set_index('Name')

# Create csv file from dictionary
df.to_csv('employees2.csv') 

It will create a csv file with name employees.csv, and all the key-value pairs in dictionary will be added into this csv file as columns. Contents of the employees.csv will be,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Summary

We learned about different ways to write a dictionary to a csv file in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top