Save Python Dictionary to CSV File



In Python to save a dictionary to a CSV file, we can use the CSV' module. This process slightly depends on the structure of your dictionary.

Generally, a CSV file refers to each line is corresponds 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 (handling files) 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 Nested Dictionaries or Dictionary of Lists: A dictionary of lists contains keys where each key is referred to as a list of values.

  • Using Dictionary with Nested Dictionaries as Values: Each key in the main dictionary leads to another dictionary.

Simple Dictionary

If the structure of your dictionary is simple (key-value pairs) then, we can save it directly, where, Keys as Columns and Values as Rows.

Example

In the below code, with the help of the open() function opening a CSV file in 'W' mode is done and csv.writer is used to handle writing the rows.

import csv

# Simply dictionary
my_dict = {'Name': 'Robert', 'Age': 27, 'City': 'Mumbai'}

# Specify the CSV file name
csv_file = 'file.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}")

Output

Dictionary saved to file.csv

Nested Dictionary

If your dictionary nested dictionaries or contains lists known as Nested Dictionary, then, we can save it in a format where each row represents an item.

Example

In the below code, each key in the dictionary corresponds to a column and each list containing the values will correspond to each row in the CSV file.

import csv

# Example dictionary of lists
Employee_dict = {
    'Employee_ID': [101,102,103],
    'NAME': ['Robert', 'John','Vikram'],
    'City': ['Mumbai', 'Chennai', 'Hyderabad']
}

# Specify the CSV file name
csv_file = 'File.csv'

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

print(f"Dictionary saved to {csv_file}")

Output

Dictionary saved to file.csv

Nested Dictionaries as Values

If the dictionary where the values are themselves dictionaries, then we might want to flatten it first which means converting this nested structure into a flat CSV format.

Example

In the below code, we are creating a nested dictionary here, the outer dictionary's keys correspond to one of the columns and the inner dictionary's key-value pairs become the remaining columns.

import csv

# Example nested dictionary
Employee_dict = {
    'Robert': {'Age': 30, 'City': 'Mumbai'},
    'John': {'Age': 25, 'City': 'Chennai'},
    'Vikram': {'Age': 35, 'City': 'Hyderabad'}
}

# Specify the CSV file name
csv_file = 'File.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 Employee_dict.items():
        row = {'Name': name}
        row.update(details)
        writer.writerow(row)

print(f"Dictionary saved to {csv_file}")

Output

Dictionary saved to File.csv
Updated on: 2024-09-23T14:29:19+05:30

44K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements