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.
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().
In Python, you can use the CSV writer's writerows() function to write multiple rows into a CSV file on the same go.
DictWriter. writeheader() is used to write a row of column headings / field names to the given 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).
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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With