在python中读取/写出字典到csv文件

时间:2021-06-05 20:30:50

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

对python来说很新,而且csv文件的文档有点令人困惑。

I have a dictionary that looks like the following:

我有一个字典,如下所示:

key1: (value1, value2)

key1:(value1,value2)

key2: (value1, value2)

key2:(value1,value2)

key3: (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.

我想将这些文件以每行包含密钥的格式写入csv文件,然后是两个值。

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

我还希望能够在以后将它们从文件中读回字典中。

3 个解决方案

#1


4  

I don't find enough reasons to use Pandas here for a relatively simple problem. Also note to OP, if you want to store the value in file and read it back go for JSON instead of CSV. Exporting to CSV will be helpful to interactive with other people(potentially Excel users).

我没有找到足够的理由在这里使用Pandas来解决一个相对简单的问题。另请注意OP,如果要将值存储在文件中并将其读回,请转到JSON而不是CSV。导出为CSV将有助于与其他人(可能是Excel用户)进行交互。

Here is how I will store it in CSV

以下是我将其存储在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()]) 
print CSV #You can store this string variable to file as you wish
# with open("filename.csv", "w") as file:
    # file.write(CSV)

This code explains what happens inside the list comrpehension.

此代码解释了list comrpehension中发生的事情。

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

#2


9  

I highly recommend Pandas for this.

我强烈推荐Pandas。

Convert to Pandas DataFrame:

转换为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:

创建CSV文件:

df.to_csv("data.csv")

Read the CSV file back as a DataFrame:

将CSV文件作为DataFrame读回:

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

Convert the DataFrame back to the original dictionary format:

将DataFrame转换回原始字典格式:

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

EDIT: Thanks to Colonel Beauvel for reminding me that you can pass the file name directly to Pandas functions.

编辑:感谢Beauvel上校提醒我你可以直接将文件名传递给Pandas函数。

EDIT2: 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.

编辑2:既然你提到了在Excel中使用输出文件的目标,那么Pandas to_excel()和read_excel()可能对你更有用,因为它们可以更好地保留转换之间的内容。此外,您可能希望完全跳过Excel并使用标准的Python科学堆栈。

#3


3  

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

我会用pandas,它可以在一行中完成:

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)

#1


4  

I don't find enough reasons to use Pandas here for a relatively simple problem. Also note to OP, if you want to store the value in file and read it back go for JSON instead of CSV. Exporting to CSV will be helpful to interactive with other people(potentially Excel users).

我没有找到足够的理由在这里使用Pandas来解决一个相对简单的问题。另请注意OP,如果要将值存储在文件中并将其读回,请转到JSON而不是CSV。导出为CSV将有助于与其他人(可能是Excel用户)进行交互。

Here is how I will store it in CSV

以下是我将其存储在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()]) 
print CSV #You can store this string variable to file as you wish
# with open("filename.csv", "w") as file:
    # file.write(CSV)

This code explains what happens inside the list comrpehension.

此代码解释了list comrpehension中发生的事情。

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

#2


9  

I highly recommend Pandas for this.

我强烈推荐Pandas。

Convert to Pandas DataFrame:

转换为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:

创建CSV文件:

df.to_csv("data.csv")

Read the CSV file back as a DataFrame:

将CSV文件作为DataFrame读回:

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

Convert the DataFrame back to the original dictionary format:

将DataFrame转换回原始字典格式:

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

EDIT: Thanks to Colonel Beauvel for reminding me that you can pass the file name directly to Pandas functions.

编辑:感谢Beauvel上校提醒我你可以直接将文件名传递给Pandas函数。

EDIT2: 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.

编辑2:既然你提到了在Excel中使用输出文件的目标,那么Pandas to_excel()和read_excel()可能对你更有用,因为它们可以更好地保留转换之间的内容。此外,您可能希望完全跳过Excel并使用标准的Python科学堆栈。

#3


3  

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

我会用pandas,它可以在一行中完成:

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)