How to write a dictionary to a CSV file in python?
One of the most common file storage formats is CSV (Comma Separated Values), which allows for a wide range of manipulations and operations. JSON (dictionary) on the other hand is useful while working with APIs and No-SQL databases. But not all are familiar with using a dictionary, hence a need to convert to a format that is readable and consumable by everyone i.e. CSV, write a dictionary to a csv file.
Introduction🔊
We’ll concentrate on converting write a dictionary to a csv file in this article. We are going to use a python library which eases the task for us. The name of the library is CSV. The in-built functions present in the library aids us to achieve the conversion of the dictionary to CSV. Let’s get forward with the implementation.
Implementation⚙️
The below snippet implements the goal to convert a dictionary to CSV.
import csv
course_header = ['index', 'Course Name', 'Creator', 'Price']
courses_dict = [
{
"index" : 1,
"Course Name": "JavaScript Under The Hood",
"Creator": "Brad Traversy",
"Price": 0,
},
{
"index" : 2,
"Course Name": "Unit and integration testing with Vitest",
"Creator": "Team codedamn",
"Price": 1499,
},
{
"index" : 3,
"Course Name": "100 Days Of Projects",
"Creator": "Team codedamn",
"Price": 0,
}
]
file_csv = "courses.csv"
try:
with open(file_csv, 'w') as csv_file:
linker = csv.DictWriter(csv_file, fieldnames = course_header)
linker.writeheader()
for course in courses_dict:
linker.writerow(course)
except IOError:
print("Error encountered...")
Code language: Python (python)
Initially, we import the csv
module. Then we declare the header(s) or column names of the CSV as a list in the variable course_header
. Then we create a dictionary courses_dict
that contains a list of dictionary that contains details or data. Then we create a variable named files_csv
that contains the name of the file that has to be saved. Make sure that it has the extension of *.csv
.
Then the usage of a try
– except
the block we open the file in write mode which is stored in the file_csv
. We create an linker
object and use a DictWriter
function available in the csv
library. it accepts two parameters. One is the file name and the other is fieldnames
. The value field names are equal to column names that are stored in course_header
. Then we write the values passed as parameters into the header of the CSV file using the writeheader()
function.
Finally, we must add the data from the dictionary to the CSV file’s rows. We employ a loop that iterates across each dictionary in the list to help the condition. The value is then passed into the writerow()
function, which adds a new row to the CSV file.
🎉We have finally added all our contents from the dictionary to the CSV successfully. If you encounter any IOError
then you will be prompted in the command prompt. Else the error will be raised.
Note: Even if we run the script any number of times the command will be overwritten as we open the file in write mode (w
).
Outputđź’»
We shall append (add) the minimal element from the unsorted sub-array to the end of the sorted sub-array to help with understanding. For the dictionary and columns used above, you could expect an output similar to:
We had three different sets of data with four columns, all of which have been converted to CSV for future use. The data that is used for reference is collected from the codedamn courses website.
Wind-Up🔚
- We’ve mastered the Python skills necessary to convert a dictionary to a CSV file.
- The different library functions are being used to carry out the required operations.
- Here is the link to the codedamn playground that contains the script used above. Also, you can find the
courses.csv
file in the files tab for reference.
Sharing is caring
Did you like what Sriniketh J wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses:
304 students learning
Haris
Python Crash Course for Beginners
Surendra varma Pericherla
Learn Data Structures Using Python