Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to save a Python Dictionary to CSV file?
In Python, to save a dictionary to a CSV file, we can use the csv module. This process depends on the structure of your dictionary.
Generally, a CSV file refers to each line corresponding to a row in a table, and each value in the line is separated by a comma. CSV files are widely used because they are easy to read and write, and also easy to transfer data in the form of strings.
Common Approaches
There are various scenarios for saving a Python Dictionary to a CSV file. In this article, we focus on some common methods as follows ?
Using Simple Dictionary (Key-Value Pairs): Collection of paired items where each unique key is referred to as value.
Using Dictionary of Lists: A dictionary where each key refers to a list of values.
Using Nested Dictionaries as Values: Each key in the main dictionary leads to another dictionary.
Using Simple Dictionary (Key-Value Pairs)
If the structure of your dictionary is simple (key-value pairs), we can save it directly with keys as one column and values as another ?
import csv
# Simple dictionary
my_dict = {'Name': 'Robert', 'Age': 27, 'City': 'Mumbai'}
# Specify the CSV file name
csv_file = 'simple_dict.csv'
# Writing to CSV file
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Key', 'Value'])
# Write data
for key, value in my_dict.items():
writer.writerow([key, value])
print(f"Dictionary saved to {csv_file}")
Dictionary saved to simple_dict.csv
Using Dictionary of Lists
If your dictionary contains lists as values, each key corresponds to a column and the lists contain row data ?
import csv
# Dictionary of lists
employee_data = {
'Employee_ID': [101, 102, 103],
'Name': ['Robert', 'John', 'Vikram'],
'City': ['Mumbai', 'Chennai', 'Hyderabad']
}
# Specify the CSV file name
csv_file = 'employee_data.csv'
# Writing to CSV file
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
# Write header
writer.writerow(employee_data.keys())
# Write data rows
rows = zip(*employee_data.values())
writer.writerows(rows)
print(f"Dictionary saved to {csv_file}")
Dictionary saved to employee_data.csv
Using Nested Dictionaries as Values
When dictionary values are themselves dictionaries, we need to flatten the structure. Here we use csv.DictWriter for better handling ?
import csv
# Nested dictionary
employees = {
'Robert': {'Age': 30, 'City': 'Mumbai'},
'John': {'Age': 25, 'City': 'Chennai'},
'Vikram': {'Age': 35, 'City': 'Hyderabad'}
}
# Specify the CSV file name
csv_file = 'nested_employees.csv'
# Writing to CSV file
with open(csv_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['Name', 'Age', 'City'])
writer.writeheader()
for name, details in employees.items():
row = {'Name': name}
row.update(details)
writer.writerow(row)
print(f"Dictionary saved to {csv_file}")
Dictionary saved to nested_employees.csv
Comparison of Methods
| Dictionary Type | CSV Writer Method | Best For |
|---|---|---|
| Simple Key-Value | csv.writer() |
Basic data conversion |
| Dictionary of Lists |
csv.writer() with zip()
|
Tabular data with columns |
| Nested Dictionaries | csv.DictWriter() |
Complex structured data |
Conclusion
Use csv.writer() for simple dictionaries and dictionary of lists. Use csv.DictWriter() for nested dictionaries as it provides better control over field mapping and headers.
