In this Python tutorial, we will understand how to save or convert Python Dictionary to a CSV file.
In Python, we can save or convert a Python dictionary to CSV using csv.DictWriter(), pandas.DataFrame.to_csv(), file.write(byte), and more.
And this Python tutorial will discuss multiple examples of using all these methods. Here is the list of topics that we will cover.
- Save Python Dictionary to CSV using DictWriter()
- Save Python Dictionary to CSV using for loop
- Convert Python dictionary to CSV using Pandas
- Python dictionary to CSV using writerows()
- Save Python Dictionary to CSV with header
Save Python Dictionary to CSV
In Python, there are multiple ways to convert or save Python Dictionary to CSV. The list of ways is listed below.
- Using CSV module
- Using Pandas module
- Using file.write() method
- Using file.writerows() method
Let us discuss each of these methods in more detail.
Save Python Dictionary to CSV using DictWriter()
The main task in converting the Python Dictionary to a CSV file is to read the dictionary data.
- And DictWriter() class which is a part of csv module helps to read and write the dictionary data into rows.
- After this, we can use the writerows() method to write the dictionary data into the csv file.
Let’s take an example and check how to convert a dictionary into a CSV file.
Source Code:
import csv
employee_info = ['emp_id', 'emp_name', 'skills']
new_dict = [
{'emp_id': 456, 'emp_name': 'George', 'skills': 'Python'},
{'emp_id': 892, 'emp_name': 'Adam', 'skills': 'Java'},
{'emp_id': 178, 'emp_name': 'Gilchrist', 'skills': 'Mongo db'},
{'emp_id': 155, 'emp_name': 'Elon', 'skills': 'Sql'},
{'emp_id': 299, 'emp_name': 'Mask', 'skills': 'Ruby'},
]
with open('test4.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = employee_info)
writer.writeheader()
writer.writerows(new_dict)
- Here we can define the ’employee_info’ list and this list will be utilized as column names.
- Now if we want to open a file in the writing mode then we can use the open() function. And to write the first line in the CSV file, we use the writerheader() method.
- In this example, the writerows() method is to write the row argument to the writer’s file object.
Once we execute the above Python program, we will get the following file as result.
Save Python Dictionary to CSV using for loop
Next, let us discuss another way to save the Python Dictionary to CSV using the For Loop in Python.
Here is an example where we will convert my_dictionary dictionary to a test6.csv file.
import csv
my_dictionary = {'values': 678, 'values2': 167, 'values6': 998}
with open('test6.csv', 'w') as f:
for key in my_dictionary.keys():
f.write("%s, %s\n" % (key, my_dictionary[key]))
In the above code, first, we will define a dictionary and use the open() function to open the file. And to write the CSV data into a file, we can use the concept of dict.keys().
Here is the result of the test6.csv file after executing the above program.
This is how to convert a dictionary into a CSV file.
Read: Python convert dictionary to an array
Convert Python dictionary to CSV using Pandas
- Let us see how to convert the Python dictionary to CSV by using the pandas module.
- In this example, we will declare a dictionary and convert it into a dataframe after that we convert it into a CSV file by using the to_csv() function.
Source Code:
import pandas as pd
new_my_dict = [
{'a': 15, 'n': 81, 'p': 177},
{'a': 18, 'n': 24, 'p': 190},
{'a': 19, 'n': 20, 'p': 156},
]
df = pd.DataFrame.from_dict(new_my_dict)
df.to_csv (r'test8.csv', index=False, header=True)
- In the above code, we need to import the pandas module and then create a dictionary ‘new_my_dict’.
- Here we are also converting the dictionary to a DataFrame using pd.DataFrame.from_dict().
- Next, we can use the to_csv() method and pass the index and header as a parameter. However, these parameters are optional and passed index as ‘false’ and header as ‘True’.
Here is the final result of the above Python program.
Read: Get all values from a dictionary Python
Python dictionary to CSV using writerows()
In the method, first, we will create a CSV file using the open() method in Python. After this, we define a dictionary and use the for loop to iterate the key-value pair of the dictionary and write it into the CSV file using writerows().
Source Code:
import csv
new_path = open("mytest.csv", "w")
file_dictionary = {"oliva":199,"james":145,"potter":187}
z = csv.writer(new_path)
for new_k, new_v in file_dictionary.items():
z.writerow([new_k, new_v])
new_path.close()
Note: In the ‘new_path’ variable you have to store your own CSV file.
Once we execute the above Python program, we will the following file result.
Read: Python dictionary of tuples
Save Python Dictionary to CSV with header
In this section, we will understand how to convert a dictionary to CSV with a header, And for this task, we will use the DictWriter() method that is used to insert data into the CSV file.
Example:
import csv
new_dictionary = { "Australia" : 456, "Germany" : 2678, "China" : 1890,"Japan":1667}
with open('maintest.csv', 'w', newline='') as csvfile:
header_key = ['Country', 'Value']
new_val = csv.DictWriter(csvfile, fieldnames=header_key)
new_val.writeheader()
for new_k in new_dictionary:
new_val.writerow({'Country': new_k, 'Value': new_dictionary[new_k]})
- In this example, we will define a dictionary named new_dictionary which will be utilized as values.
- And to the header section, we defined the header_key list.
- After this, we use the open() function to open the file and used the concept of dictwriterheader() method to pass a field name keyword as an argument.
Here is the Output of the following given code
Also, take a look at some more Python tutorials.
- Python find max value in a dictionary
- Python Dictionary Count + Examples
- Python dictionary get() method [With Examples]
- Python shutil copy file + Examples
In this Python tutorial, we have discussed the Python dictionary to CSV. Here we have also covered the following examples:
- Save Python Dictionary to CSV using DictWriter()
- Save Python Dictionary to CSV using for loop
- Convert Python dictionary to CSV using Pandas
- Python dictionary to CSV using writerows()
- Save Python Dictionary to CSV with header
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.