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
The dictionary has been successfully saved as a CSV file.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.