To save a Python Dictionary to a CSV file, import the built-in csv module and use the csv.DictWriter() method. The csv.DictWriter() maps dictionary keys to CSV column headers.
Then, we can use the writeheader() method to write the header row and writerow() method to write the dictionary values.
Let’s say we have one dictionary (single key–value pair), we can save it as a single row in CSV.
import csv
order = {'name': 'Kaynes', 'price': 6704.50, 'city': 'New York'}
with open('single_dict.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=order.keys())
writer.writeheader()
writer.writerow(order)
print("CSV file is saved successfully!")
# Output: CSV file is saved successfully!
Multiple Dictionaries (List of Dicts)
If you have a list of dictionaries, each dictionary becomes a row in a CSV file.
import csv
orders = [
{'name': 'Kaynes', 'price': 6704.50, 'city': 'New York'},
{'name': 'Netweb', 'price': 4031.00, 'city': 'Delhi'},
{'name': 'VMM', 'price': 144.89, 'city': 'Rajkot'},
{'name': 'V2', 'price': 2442.00, 'city': 'Oslo'},
]
with open('multiple_dict.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=orders[0].keys())
writer.writeheader()
writer.writerows(orders)
print("Multiple Dictionaries saved as CSV File!")
# Output: Multiple Dictionaries saved as CSV File!
In this code, we define a list of dictionaries, where each dictionary has three properties that represent rows when converted to a CSV file.
For defining the header of the CSV file, use fieldnames=orders[0].keys() argument.
For writing multiple rows, we used the .writerows() method.
Dictionary with nested values to a csv file
Inner dictionaries can’t be written directly; they must be flattened manually or converted to JSON strings.
import csv
main_dict = {'id': 1, 'details': {'color': 'red', 'size': 'large'}}
with open('nested.csv', 'w', newline='') as file:
writer = csv.writer(file)
row = [main_dict['id'], '|'.join(
[f"{k}:{v}" for k, v in main_dict['details'].items()])]
writer.writerow(['id', 'details'])
writer.writerow(row)
print("Nested dictionary written to CSV successfully.")
# Output: Nested dictionary written to CSV successfully.
In this code, we have a dictionary with nested values, such as lists. So, we need to format them properly before writing them to a CSV file. We have formatted row values with the help of join() and dict.items() method.
That’s all!



