How to save a Python Dictionary to CSV file?


CSV (Comma Separated Values) is a most common file format that is widely supported by many platforms and applications.

Use csv module from Python's standard library. Easiest way is to open a csv file in 'w' mode with the help of open() function and write  key value pair in comma separated form.

import csv
my_dict = {'1': 'aaa', '2': 'bbb', '3': 'ccc'}
with open('test.csv', 'w') as f:
    for key in my_dict.keys():
        f.write("%s,%s\n"%(key,my_dict[key]))

The csv module contains DictWriter method that requires name of csv file to write and a list object containing field names. The writeheader() method writes first line in csv file as field names. The subsequent for loop writes each row in csv form to the csv file.

import csv
csv_columns = ['No','Name','Country']
dict_data = [
{'No': 1, 'Name': 'Alex', 'Country': 'India'},
{'No': 2, 'Name': 'Ben', 'Country': 'USA'},
{'No': 3, 'Name': 'Shri Ram', 'Country': 'India'},
{'No': 4, 'Name': 'Smith', 'Country': 'USA'},
{'No': 5, 'Name': 'Yuva Raj', 'Country': 'India'},
]
csv_file = "Names.csv"
try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        writer.writeheader()
        for data in dict_data:
            writer.writerow(data)
except IOError:
    print("I/O error")

Updated on: 24-Aug-2023

38K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements