Read / write 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 this:

key1: (value1, value2)

key2: (value1, value2)

key3: (value1, value2) ....

I would like to write them to a csv file in a format where each line contains a key and then two values.

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

+8
source share
3 answers

I did not find enough benefit to use pandas here, as the problem is simple.

Also pay attention to the OP, if you want to save the values ​​in a read-only file, just use the JSON or Python shelf module. Export to CSV should be minimized only when we need to interact with potential Excel users.

The code below converts words to 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 
+5
source

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 is to use the output file in Excel, Pandas to_excel () and read_excel () may be more useful to you as they better preserve content between conversions. Alternatively, you can skip Excel altogether and use the standard Python science stack .

+17
source

I would use pandas, this can be done on 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) 
+4
source

Source: https://habr.com/ru/post/1238318/


All Articles