Sometimes, we want to write a Python dictionary to a csv file.
In this article, we’ll look at how to write a Python dictionary to a csv file.
How to write a Python dictionary to a csv file?
To write a Python dictionary to a csv file, we can use the csv.DictWriter
class.
For instance, we write
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'w') as f:
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
to call open
to open mycsvfile.csv with write permission.
Then we create the DictWriter
object with the file f
and the keys of my_dict
as column names.
Then we call writeheader
to write the column name as headers.
And then we call writerow
to write the my_dict
dict’s values as a row.
Conclusion
To write a Python dictionary to a csv file, we can use the csv.DictWriter
class.