How to Save Python Dictionary to a CSV File?

Today, during a webinar, some asked about converting a Python dictionary to csv. There are various methods to do so. In this tutorial, I will explain how to save a Python dictionary to a CSV file with examples.

To convert a Python dictionary to a CSV file using the csv module, you first import the module and prepare your dictionary. Open a CSV file in write mode, create a csv.writer object, and write the dictionary keys as the header row. Then, use writer.writerows(zip(*your_dict.values())) to write the dictionary values row by row. This method efficiently transposes the dictionary data into a CSV format.

What is a CSV File?

CSV (Comma-Separated Values) files are a popular format for storing tabular data. Each line in a CSV file corresponds to a row in the table, and a comma separates each value. CSV files are widely used because they are simple and compatible with many applications, including Microsoft Excel and Google Sheets.

Why Convert a Dictionary to CSV?

Python dictionaries are data structures that store key-value pairs. However, CSV files are often more practical when it comes to data analysis and sharing. Converting a dictionary to a CSV file allows you to easily share data with others and import it into various data analysis tools.

Dict to CSV in Python

There are various methods in Python to convert a dictionary to CSV. Let me explain each method with examples.

Method 1: Using the CSV Module

The CSV module in Python provides functionality that allows users to both read from and write to CSV files. This is one of the best and recommended methods to convert dict to CSV in Python.

Let me show you an example.

Example: Exporting Sales Data

Let’s say we have sales data stored in a dictionary, and we want to export it to a CSV file.

import csv

sales_data = {
    "Date": ["2023-09-01", "2023-09-02", "2023-09-03"],
    "Product": ["Laptop", "Smartphone", "Tablet"],
    "Units Sold": [5, 10, 7],
    "Revenue": [5000, 7000, 3500]
}

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

# Writing to CSV file
with open(filename, mode='w', newline='') as file:
    writer = csv.writer(file)
    # Write the header
    writer.writerow(sales_data.keys())
    # Write the data rows
    writer.writerows(zip(*sales_data.values()))

print(f"Data successfully written to {filename}")

In this example, we use the csv.writer to write the dictionary data to a CSV file. The zip(*sales_data.values()) function transposes the dictionary values, making it easy to write each row to the file.

I executed the above Python code, and you can see that it generated the CSV file with the data. Look at the screenshot for reference.

dict to csv python

Check out Find Duplicate Values in Dictionary Python

Method 2: Using the Pandas Library

Pandas is a powerful data manipulation library that provides an easy-to-use interface for handling structured data. It can be particularly useful for converting dictionaries to CSV files.

Let me show you an example.

Example: Exporting Employee Data

Consider a scenario where we have employee data stored in a dictionary.

import pandas as pd

employee_data = {
    "Name": ["John Doe", "Jane Smith", "Emily Davis"],
    "Department": ["HR", "IT", "Finance"],
    "Salary": [60000, 80000, 75000]
}

# Convert dictionary to DataFrame
df = pd.DataFrame(employee_data)

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

# Write DataFrame to CSV file
df.to_csv(filename, index=False)

print(f"Data successfully written to {filename}")

In this example, we first convert the dictionary to a Pandas DataFrame and then use the to_csv method to write the DataFrame to a CSV file. The index=False parameter ensures that the row indices are not included in the CSV file.

Check out Create a Dictionary with Multiple Values Per Key

Method 3: Using csv.DictWriter

The csv.DictWriter class allows you to write dictionaries to a CSV file, where each dictionary represents a row. Here is an example.

Example: Exporting Product Inventory

Let’s export product inventory data stored in a list of dictionaries.

import csv

inventory_data = [
    {"Product ID": 101, "Product Name": "Laptop", "Stock": 50},
    {"Product ID": 102, "Product Name": "Smartphone", "Stock": 120},
    {"Product ID": 103, "Product Name": "Tablet", "Stock": 75}
]

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

# Writing to CSV file
with open(filename, mode='w', newline='') as file:
    # Create a DictWriter object
    writer = csv.DictWriter(file, fieldnames=inventory_data[0].keys())
    # Write the header
    writer.writeheader()
    # Write the data rows
    writer.writerows(inventory_data)

print(f"Data successfully written to {filename}")

In this example, we use the csv.DictWriter to write a list of dictionaries to a CSV file. Each dictionary in the list represents a row in the CSV file.

I executed the above Python code, and you can see the output in the screenshot below:

python dict to csv

Conclusion

You can convert a Python dictionary to a CSV file using different methods, such as using the csv module, the pandas library, and using the csv.DictWriter class. I have also provided a few examples of converting a dictionary to CSV in Python. If you still have any questions, feel free to leave a comment below.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.