How to save a Python Dictionary to CSV file?

PythonServer Side ProgrammingProgramming

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():

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"
    with open(csv_file, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        for data in dict_data:
except IOError:
    print("I/O error")
Published on 04-May-2021 20:38:03