Menu Close

How to Convert Dictionary to CSV in Python

How to convert dictionary to csv in Python

In this article, I will give a complete guide to convert Dictionary to CSV in Python with the help of examples. Here we will use Python standard library that is CSV to write Python Dictionary to CSV file.

A CSV file is the most common and popular file format that is supported by many platforms and applications.A .csv file contains values commas-separated and new line.Python provides a built-in module csv that gives us the power to work with any type of CSV file.

How to Convert Dictionary to CSV in Python

To save a dictionary to CSV in Python we need to just import the Python CSV module using the import keyword. Python CSV module provides various methods to write Python Dictionary to CSV.

Let’s see all the processes one by one.

Firstly, we need to import csv module.

import csv

Define Python Dictionary.

Here we will define a simple Python dictionary named dict.

dict = {"Name": "Vishvajit Rao", "age": 23, "Occupation": "Developer","Skills": "Python"}

Example: Write Python Dictionary to CSV file


import csv

dict = {"Name": "Vishvajit Rao", "age": 23, "Occupation": "Developer","Skills": "Python"}
file = open("sample.csv", "w")

# make write object
writer = csv.writer(file)

for key, value in dict.items():
    writer.writerow([key, value])

file.close()

We have another option to write CSV files without CSV modules let’s see how can we do that.

Example:


dict = {"Name": "Vishvajit Rao", "age": 23, "Occupation": "Developer","Skills": "Python"}

with open("sample.csv", 'w') as file:
    for key, value in dict.items():
        file.write(f"{key},{value}\n")

Output:


Name,Vishvajit Rao
age,23
Occupation,Developer
Skills,Python

Python csv.DictWriter()

This function creates an object that acts as a write object and maps dictionary into rows. It accepts file object and field names as a parameter.

writer = csv.DictWriter(file_object, fieldname)

Python csvwriter.WriteHeader()

Python csv.WriteHeader() function is responsible for writing header ( row ) in csv file that identify each column data in csv files.

writer.WriteHeader()

Python csvwriter.writerow()

This method is responsible for writing each dictionary of the list into a CSV row according to the header.


import csv
students = [{"Name": "Vishvajit Rao", "Age": 23, "Occupation": "Developer","Skills": "Python"},
{"Name": "John", "Age": 33, "Occupation": "Front End Developer","Skills": "Angular"},
{"Name": "Harshita", "Age": 21, "Occupation": "Tester","Skills": "Selenium"},
{"Name": "Mohak", "Age": 30, "Occupation": "Full Stack","Skills": "Python, React and MySQL"}]

field_name = ["Name", "Age", "Occupation", "Skills"]
filename = "sample.csv"

# write object
with open(filename, "w") as file:
    writer = csv.DictWriter(file, fieldnames=field_name)
    writer.writeheader()
    for row in students:
        writer.writerow(row)

Output:


Name,Age,Occupation,Skills
Vishvajit Rao,23,Developer,Python
John,33,Front End Developer,Angular
Harshita,21,Tester,Selenium
Mohak,30,Full Stack,"Python, React and MySQL"

Python csvwriter.writerows()

csvwriter.writerows() function is responsible for writing a whole list of dictionaries into rows inside CSV files.There is no need to interact with each dictionary on the list. Let see.

Example


import csv
students = [{"Name": "Vishvajit Rao", "Age": 23, "Occupation": "Developer","Skills": "Python"},
{"Name": "John", "Age": 33, "Occupation": "Front End Developer","Skills": "Angular"},
{"Name": "Harshita", "Age": 21, "Occupation": "Tester","Skills": "Selenium"},
{"Name": "Mohak", "Age": 30, "Occupation": "Full Stack","Skills": "Python, React and MySQL"}]

field_name = ["Name", "Age", "Occupation", "Skills"]
filename = "sample.csv"

# write object
with open(filename, "w") as file:
    writer = csv.DictWriter(file, fieldnames=field_name)
    writer.writeheader()
	writer.writerows(students)

Output


Name,Age,Occupation,Skills
Vishvajit Rao,23,Developer,Python
John,33,Front End Developer,Angular
Harshita,21,Tester,Selenium
Mohak,30,Full Stack,"Python, React and MySQL"

Conclusion

In this article, we have seen all about how to convert Dictionary to CSV in Python with the help of multiple examples. Here we have used Python built-in module CSV to write Python Dictionary to CSV. As a Python developer, you must have knowledge of how to save Dictionary to CSV files.

I hope after this article, you don’t have any confusion regarding how to convert Dictionary to CSV. If you like this article, please share and keep visiting for further interesting tutorials.

Thanks for reading. 👏👏

How to install pgAdmin 4 in Windows
How to convert SQL Query Result to Pandas DataFrame

Related Posts