Reading/Writing out a dictionary to csv file in python

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.


I didn't find enough benefit to use Pandas here since the problem is simple.

Also note to OP, if you want to store values to a file just for reading it back simply use JSON or Python's shelve module. Exporting to CSV should be minimised only when we need to interact potentially Excel users.

The below code converts a dict into CSV

value1 = 'one'
value2 = 'two'
d = { 
        'key1': (value1, value2), 
        'key2': (value1, value2), 
        'key3': (value1, value2)
    }
CSV ="\n".join([k+','+','.join(v) for k,v in d.items()]) 
#You can store this CSV string variable to file as below
# with open("filename.csv", "w") as file:
    # file.write(CSV)

This code explains what happens inside the list comprehension.

CSV = ""
for k,v in d.items():
    line = "{},{}\n".format(k, ",".join(v))
    CSV+=line
print CSV