How to convert a dictionary to a CSV file in Python
How to convert a dictionary to a CSV file in Python.
Here's a step-by-step tutorial on how to convert a dictionary to a CSV file in Python.
Step 1: Import the necessary modules
To work with CSV files, we need to import the csv module.
import csv
Step 2: Create a dictionary
Create a dictionary that you want to convert to a CSV file. For this tutorial, let's create a simple dictionary with some sample data.
data = {'Name': ['John', 'Emma', 'Mike'],
'Age': [25, 28, 30],
'Country': ['USA', 'Canada', 'Australia']}
Step 3: Define the CSV file path
Decide on the file path where you want to save the CSV file. For example, let's save it as 'data.csv' in the current working directory.
csv_file = 'data.csv'
Step 4: Open the CSV file in write mode
Open the CSV file in write mode using the open() function and create a csv.writer object.
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
Step 5: Write the header row
Write the header row to the CSV file using the writerow() method. The header row contains the keys from the dictionary.
header = data.keys()
writer.writerow(header)
Step 6: Write the data rows
Iterate through the values in the dictionary and write each row to the CSV file using the writerow() method.
for row in zip(*data.values()):
writer.writerow(row)
Step 7: Complete the conversion
Close the file after writing all the data rows to complete the conversion.
file.close()
Step 8: Verify the CSV file
You can now open the generated CSV file ('data.csv') to verify the data.
Here's the complete code:
import csv
data = {'Name': ['John', 'Emma', 'Mike'],
'Age': [25, 28, 30],
'Country': ['USA', 'Canada', 'Australia']}
csv_file = 'data.csv'
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
header = data.keys()
writer.writerow(header)
for row in zip(*data.values()):
writer.writerow(row)
file.close()
That's it! You have successfully converted a dictionary to a CSV file in Python.