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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34301088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:46:32  来源:igfitidea点击:

Reading/Writing out a dictionary to csv file in python

pythoncsvdictionary

提问by SlightlyCultured

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

对 python 来说很新,而且 csv 文件的文档有点混乱。

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.

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

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

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

采纳答案by nehem

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

我没有发现在这里使用 Pandas 的好处,因为问题很简单。

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.

另请注意 OP,如果您想将值存储到文件中仅用于读取它,只需使用 JSON 或 Python 的 shelve 模块。仅当我们需要与潜在的 Excel 用户进行交互时,才应最小化导出到 CSV 的内容。

The below code converts a dict into CSV

以下代码将 dict 转换为 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 

回答by Martin Valgur

I highly recommend Pandasfor this.

为此,我强烈推荐Pandas

Convert to Pandas DataFrame:

转换为 Pandas 数据帧:

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

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

回答by Colonel Beauvel

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)