Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading/Writing out a dictionary to csv file in python

Pretty new to python, and the documentation for csv files is a bit confusing.

I have a dictionary that looks like the following:

key1: (value1, value2)

key2: (value1, value2)

key3: (value1, value2)
....

I would like to write these out to a csv file in the format where each line contains the key, followed by the two values.

I would also like to be able to read them back into a dictionary from the file at a later date.

like image 536
SlightlyCultured Avatar asked Dec 15 '15 23:12

SlightlyCultured


People also ask

How do you write a dictionary to a .csv in Python?

In Python to convert a dictionary to CSV use the dictwriter() method. This method is used to insert data into the CSV file. In Python, the CSV module stores the dictwriter() method. It creates an object and works like the dictwriter().

Can you write directly to a CSV file in Python?

In Python, you can use the CSV writer's writerows() function to write multiple rows into a CSV file on the same go.

Which function is used to write a dictionary into a CSV file?

DictWriter. writeheader() is used to write a row of column headings / field names to the given CSV file.

How do I append a dictionary to a CSV file?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).


2 Answers

I highly recommend Pandas for this.

Convert to Pandas DataFrame:

import pandas as pd

d = {
    'a': (1, 101),
    'b': (2, 202),
    'c': (3, 303)
}
df = pd.DataFrame.from_dict(d, orient="index")

Create a CSV file:

df.to_csv("data.csv")

Read the CSV file back as a DataFrame:

df = pd.read_csv("data.csv", index_col=0)

Convert the DataFrame back to the original dictionary format:

d = df.to_dict("split")
d = dict(zip(d["index"], d["data"]))

EDIT: Since you mention that your goal to use the output file in Excel, Pandas to_excel() and read_excel() might be more useful to you since they better-preserve the content between conversions. Also, you might want skip Excel altogether and use the standard Python scientific stack.

like image 139
Martin Valgur Avatar answered Oct 06 '22 23:10

Martin Valgur


I would use pandas, it can be done in one line:

import pandas as pd

dic = {'key1':['v1','v2'], 'key2':['vv','gg']}

pd.DataFrame(dic).T.reset_index().to_csv('myfile.csv', header=False, index=False)
like image 21
Colonel Beauvel Avatar answered Oct 06 '22 22:10

Colonel Beauvel