How to do write Python dictionary to CSV

Python Dictionary

In this post, we are going to understand How to write a Python dictionary to CSV. We are going to use the python built-in CSV Module. To read and write a CSV file in Python CSV Module provides reader() and writer() methods. To use these first we need to import this module in our program by using the import CSV.

1. Write Python dictionary to CSV


In this example, we are opening a file in writing mode by using open() method.Creating CSV writer object using writer() method of csv module.Using the for loop, we are Iterating over dictionary key,values using dictionary .item() method(Student_dict.items()) .The CSV Module writerow() method is used to write a row to csv file.

import csv
Student_dict = {'Name': 'Jack','Mark': 100, 'Subject': 'Math'}



with open('students.csv', 'w') as file:
    writer = csv.writer(file)
    for key, value in Student_dict.items():
       writer.writerow([key, value])   

Output

Name	Jack
	
Mark	100
	
Subject	Math

2. Write list of dictionaries to CSV with headers


The CSV module’s dictwriter() method takes the name of the CSV file and list of columns name and then writeheader() method writes the first rows of columns in CSV file which is the header row.

The writerow() method to write the subsequent rows in the CSV file.

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

3. Write Dictionary of lists to CSV


In this example, we are creating an object of CSV writer using the writer() method. We passed two arguments filename and delimiter to this function. The writerow() is used to write to file the first rows of the column name in CSV File.

Then we are using the for loop with writerow() methods to write rows to the CSV file.

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

columname = Student_dict.keys()
Total_rows = len(Student_dict[list(columname)[0]])

with open('Example.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    csvwriter.writerow(columname)
    for row in range(Total_rows):
        csvwriter.writerow([Student_dict[key][row] for key in columname])

Output

Name,Marks,Subject
Jack,100,Math
Rack,100,Math
Max,100,Music
David,100,Physic

4. Pandas to write dictionary of lists to CSV


In this example, we are using the Python Pandas module to write a dictionary of lists to a CSV file. First creating Dataframe from the dictionary by using the DataFrame() constructor. Finally using the Pandas to_csv() method to write dataframe to CSV.

import pandas as pd 
Student_dict = {
    'Name': ['Jack', 'Rack', 'Max', 'David'],
    'Marks':[100,100, 100,100],
    'Subject': ['Math', 'Math', 'Music', 'Physic']
}




df = pd.DataFrame(Student_dict)
  
df.to_csv('studentdata.csv')

Output

,Name,Marks,Subject
0,Jack,100,Math
1,Rack,100,Math
2,Max,100,Music
3,David,100,Physic

5. Convert Nested Dictionaries to CSV


In this example, we are writing nested dictionaries to CSV with a header by using the CSV dictwriter() method and by using loop over the key and values of the dictionary using the Student_dict.items() method.

Writing each row of dictionary using CSV module writerow() method.

import csv
import itertools
import sys

columns= ['Name','Mark','Subject']
Student_dict = {'student1':{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
 'student2':{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
'student3':{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
'student4':{ 'Name': 'David', 'Mark':100,'Subject': 'Math'}

}



writer = csv.DictWriter( sys.stdout, columns )

for key,val in sorted(Student_dict.items()):
       row = {'Name':key}
       row.update(val)
       writer.writerow(row)  

Output

Jack,100,Math

Rack,100,Math

Max,100,Music

David,100,Math

6.Pandas to write nested dictionaries to CSV


In this example, we are using the Python Pandas module to write nested dictionaries to CSV. First creating Dataframe from the dictionary by using the DataFrame() constructor. Finally using the to_csv() method to write dataframe to CSV.

import csv
Student_dict = {'student1':{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
 'student2':{ 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'},
'student3':{ 'Name': 'Max', 'Mark': 100,'Subject': 'Music'},
'student4':{ 'Name': 'David', 'Mark':100,'Subject': 'Math'}

}

df = pd.DataFrame(Student_dict)
  
df.to_csv('studentdata.csv')

Output

	student1	student2	student3	student4
Name	Jack	Rack	Max	David
Mark	100	100	100	100
Subject	Math	Math	Music	Math

Summary

In this post we have learned multiple ways to write a Python dictionary, list of dictionaries, Dictionaries of list, nested dictionaries to CSV files by using the Python built-in module CSV and use its methods like writer(), dictwriter(), and writerow(), writeheader(). We have also used the Pandas module to write a dictionary to CSV, a list of dictionaries to CSV, nested dictionaries.