在python中读/写字典到csv文件 [英] Reading/Writing out a dictionary to csv file in python

查看:200
本文介绍了在python中读/写字典到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于python来说还很新,并且csv文件的文档有些混乱.

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

我想以每行包含密钥,然后是两个值的格式将它们写到一个csv文件中.

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.

推荐答案

由于问题很简单,我没有发现在这里使用Pandas的足够好处.

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

还要注意OP,如果要将值存储到文件中只是为了回读,只需使用JSON或Python的shelve模块即可.仅当我们需要与潜在的Excel用户进行交互时,才应将导出到CSV的操作最小化.

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.

下面的代码将字典转换为CSV

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 

这篇关于在python中读/写字典到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆