How to write list of dictionaries to CSV in Python

Python Dictionary

In this post, we are going to learn how to write a list of dictionaries to CSV in Python. The Python CSV module is used to manipulate CSV.So first we need to import this module into our code. We will use the CSV module dictwriter() method. So let us understand this with examples.

Python CSV dictwriter() method


The dictwriter() method is used to write a dictionary to CSV. It maps the dictionaries into CSV file rows.

Syntax

csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

Parameters

  • Fieldnames :This represents the sequence of key that recognise the order in which values in dictionary are passed to the writerow() method or identify the column name write to CSV file.
  • restval: The value to be written if the dictionary is missing a key in fieldnames.
  • extrasaction: This parameter indicates what action to take. If extrasaction is set to ‘raise’, the default value, a ValueError is raised. If it is set to ‘ignore’, extra values in the dictionary are ignored.

1. Write list of dictionaries to CSV with Custom headers


First, we need to import the CSV module to use all its methods and convert lists of dictionaries to CSV. The CSV module’s dictwriter() method takes the name of the CSV file and a list of columns’ names as an argument. This can be used for a directory or multiple dictionaries, nested dictionaries.

The writeheader() method writes the first rows of the column name in the CSV file that is the header row.

Now we need to write data to CSV. The writerow() method is used to write the single row at a time and map the dictionary into CSV rows.

Python code to list of dictionaries to CSV with headers

import csv
columns = ['Name','Mark','Subject']
Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
{ 'Name': 'David', 'Mark':100,'Subject': 'Math'},
{ 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'},
]
 
try:
    with open("students.csv", 'w',newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=columns)
        writer.writeheader()
        for key in Student_dict:
            writer.writerow(key)
except IOError:
    print("I/O error")

Output

Name,Mark,Subject
Jack,100,Math
Rack,100,Math
Max,100,Music
David,100,Math
Tawn,100,Physic

2.Write list of dictionaries to CSV with headers


In this example, we are using the CSV module dictwriter class to create an object of dictwrite using CSV.DictWriter(file, keys) .The writeheader() method writes the first rows of the column names in the CSV file that is the header row.

The writerows() method is used to write multiple rows at a time. Instead of looping through the key, we are the whole dictionary in one go.

Program code

import csv 


Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
{ 'Name': 'David', 'Mark':100,'Subject': 'Math'},
{ 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'},
]



keys = Student_dict[0].keys()

with open("students.csv", "w") as file:
 csvwriter = csv.DictWriter(file, keys)
 csvwriter.writeheader()
 csvwriter.writerows(Student_dict)

Output

Name	Mark	Subject
		
Jack	100	   Math
		
Rack	100	    Math
		
Max	    100	  Music
		
David	100	   Math
		
Tawn	100	Physic

3.Write list of dictionaries to CSV with missing field value


The value of column ‘Age’ is not present in the dictionary from for that reason the value pass to restval=”NA” is used for the ‘Age’ column. You can pass any value as per need.

Program code

import csv
columns = ['Name','Mark','Subject','Age']
Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
{ 'Name': 'David', 'Mark':100,'Subject': 'Math'},
{ 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'},
]


with open("student.csv", "w") as File:
  csvwriter = csv.DictWriter(File, fieldnames=columns, restval="NA")

  csvwriter.writeheader() # write header

  csvwriter.writerows(Student_dict)

Output

Name	Mark	Subject	Age
			
Jack	100	   Math	    NA
			
Rack	100	  Math	    NA
			
Max	    100	  Music	    NA
			
David	100	  Math	   NA
			
Tawn	100	 Physic    NA

4.Write of dictionaries by ignoring extra value


In this example, the dictionary contains the value for key ‘Subject’ but that is not present in the column name. So to ignore it while creating a CSV we can use extrasaction argument of dictwriter() method as we have passed in the below example extrasaction=’ignore’.

Program code

import csv
columns = ['Name','Mark']
Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
{ 'Name': 'David', 'Mark':100,'Subject': 'Math'},
{ 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'},
]


with open("student.csv", "w") as File:
  csvwriter = csv.DictWriter(File, fieldnames=columns, restval="NA",extrasaction='ignore')

  csvwriter.writeheader() # write header

  csvwriter.writerows(Student_dict)

Output

Name	Mark
	
Jack	100
	
Rack	100
	
Max	100
	
David	100
	
Tawn	100

Summary

In this post, we have explored the multiple ways of how to write a list of dictionaries to CSV in Python by using the CSV module CSV dictwriter() method.