How can I convert a Python dictionary to a CSV file?

Published on Aug. 22, 2023, 12:16 p.m.

To convert a Python dictionary to a CSV file, you can use the csv.DictWriter class from the csv module. Here’s an example:

import csv

my_dict = {'name': 'Bob', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()

with open('my_dict.csv', 'w', newline='') as f:
    dict_writer = csv.DictWriter(f, fieldnames=keys)
    dict_writer.writeheader()
    dict_writer.writerow(my_dict)

In this example, we have a dictionary called my_dict with some data, and we use the keys() method to get a list of the dictionary keys. Then we open a file called my_dict.csv in write mode using a with statement to ensure it gets closed properly.

We create a csv.DictWriter object called dict_writer, passing in the fieldnames (which are just the dictionary keys). We call the writeheader() method to write the column headers to the CSV file, and then call writerow() to write the data from the dictionary to the file.

When you run this code, it will create a file called my_dict.csv in the current directory with the following contents:

name,age,city
Bob,30,New York

If you have multiple dictionaries to write to the CSV file, you can call writerows() with a list of dictionaries instead of calling writerow() for each dictionary.

convert a Python dictionary to a CSV use pandas

Yes, you can use the pandas library to convert a Python dictionary to a CSV file. Here is an example code snippet:

import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)

df.to_csv('output.csv', index=False)

In this example, we first create a Python dictionary data with three keys - ‘name’, ‘age’, and ‘city’. Each key has a list of values associated with it. We then create a pandas DataFrame from the dictionary using the pd.DataFrame() function. Finally, we use the to_csv() method of the DataFrame to write the data to a CSV file named ‘output.csv’.

The index parameter is set to False, which means that the row numbers are not included in the CSV file. If you want the row numbers to be included, you can set index to True (which is the default value).

Note that it’s also possible to use the csv module in the Python standard library to write a CSV file from a dictionary, but using pandas can be more convenient, especially for more complex data structures.

Tags: