How to Convert(Save) Python Dictionary to CSV File

To convert a dictionary to csv in Python, you can use the csv.DictWriter() method.

Here is the step-by-step guide:

Step 1: Import CSV module

import csv

Step 2: Define the data

tech_companies_data = [
 {"Company": "Apple", "Founded": 1976, "Headquarters": "Cupertino, California, USA"},
 {"Company": "Microsoft", "Founded": 1975, "Headquarters": "Redmond, Washington, USA"},
 {"Company": "Google", "Founded": 1998, "Headquarters": "Mountain View, California, USA"},
 {"Company": "Amazon", "Founded": 1994, "Headquarters": "Seattle, Washington, USA"},
 {"Company": "Meta", "Founded": 2004, "Headquarters": "Menlo Park, California, USA"}
]

Step 3: Set the CSV file name

filename = "tech_companies_data.csv"

Step 4: Writes to the CSV file

We can open the file in write mode (‘w‘). The newline=” parameter is used to prevent extra blank lines in the CSV file, a common issue on some platforms.

First, we need to initialize a csv.DictWriter object, passing in the file object and the fieldnames.

Each dictionary in the list represents a row in the CSV file, with the keys acting as column headers and the values as the corresponding data.

Writes the column headers using writer.writeheader() method.

We then iterate over each dictionary (each row) and write it to the CSV file using the writer.writerow() method.

with open(filename, 'w', newline='') as csvfile:
 writer = csv.DictWriter(csvfile, fieldnames=tech_companies_data[0].keys())

 writer.writeheader()

 for row in tech_companies_data:
  writer.writerow(row)

Complete Example

import csv

# dictionary
tech_companies_data = [
 {"Company": "Apple", "Founded": 1976, "Headquarters": "Cupertino, California, USA"},
 {"Company": "Microsoft", "Founded": 1975, "Headquarters": "Redmond, Washington, USA"},
 {"Company": "Google", "Founded": 1998, "Headquarters": "Mountain View, California, USA"},
 {"Company": "Amazon", "Founded": 1994, "Headquarters": "Seattle, Washington, USA"},
 {"Company": "Meta", "Founded": 2004, "Headquarters": "Menlo Park, California, USA"}
]

# Specify the CSV file name
filename = "tech_companies_data.csv"

# Writing to a CSV file
with open(filename, 'w', newline='') as csvfile:
 writer = csv.DictWriter(csvfile, fieldnames=tech_companies_data[0].keys())

 # Write the headers
 writer.writeheader()

 # Write the data rows
 for row in tech_companies_data:
  writer.writerow(row)

print("The dictionary has been successfully saved as a CSV file.")

Output

tech_companies_data_csv

The dictionary has been successfully saved as a CSV file.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.