Python:为每个'key:value'一行写一个字典到一个csv文件

我有一本字典:

mydict = {key1: value_a, key2: value_b, key3: value_c}

我想以这种风格将数据写入文件dict.csv:

 key1: value_a key2: value_b key3: value_c 

我写了:

 import csv f = open('dict.csv','wb') w = csv.DictWriter(f,mydict.keys()) w.writerow(mydict) f.close() 

但是现在我把所有的键都放在一行中,而所有的值放在下一行。

当我设法写这样一个文件,我也想读回到一个新的字典。

只是为了解释我的代码,字典包含textctrls和checkbox(使用wxpython)的值和布尔值。 我想添加“保存设置”和“加载设置”button。 保存设置应该以上述方式将字典写入文件(为了使用户更容易直接编辑csv文件),加载设置应该从文件中读取并更新文本框和checkbox。

DictWriter不能按照您的预期工作。

 with open('dict.csv', 'wb') as csv_file: writer = csv.writer(csv_file) for key, value in mydict.items(): writer.writerow([key, value]) 

读回来:

 with open('dict.csv', 'rb') as csv_file: reader = csv.reader(csv_file) mydict = dict(reader) 

这是相当紧凑的,但它假设你不需要做任何types转换时阅读

最简单的方法是忽略csv模块并自己设置格式。

 with open('my_file.csv', 'w') as f: [f.write('{0},{1}\n'.format(key, value)) for key, value in my_dict.items()] 
 outfile = open( 'dict.txt', 'w' ) for key, value in sorted( mydict.items() ): outfile.write( str(key) + '\t' + str(value) + '\n' ) 

你可以做:

 for key in mydict.keys(): f.write(str(key) + ":" + str(mydict[key]) + ","); 

所以你可以拥有

key_1:value_1,key_2:value_2

我个人总是发现csv模块很烦人。 我希望有人会告诉你如何做到这一点,但我的快速和肮脏的解决scheme是:

 with open('dict.csv', 'w') as f: # This creates the file object for the context # below it and closes the file automatically l = [] for k, v in mydict.iteritems(): # Iterate over items returning key, value tuples l.append('%s: %s' % (str(k), str(v))) # Build a nice list of strings f.write(', '.join(l)) # Join that list of strings and write out 

但是,如果你想读回来,你需要做一些恼人的parsing,特别是如果它在一行。 这里有一个使用你提出的文件格式的例子。

 with open('dict.csv', 'r') as f: # Again temporary file for reading d = {} l = f.read().split(',') # Split using commas for i in l: values = i.split(': ') # Split using ': ' d[values[0]] = values[1] # Any type conversion will need to happen here 

只要给出一个选项,写一个字典到csv文件也可以用pandas包来完成。 用给定的例子可能是这样的:

mydict = {'key1': 'a', 'key2': 'b', 'key3': 'c'}

 import pandas as pd (pd.DataFrame.from_dict(data=mydict, orient='index'). to_csv('dict_file.csv', header=False)) 

要考虑的主要问题是在from_dict方法中将'orient'参数设置为'index'。 这使您可以select是否要将每个字典密钥写入新行。

另外,在to_csv方法中,header参数设置为False,只是让字典元素没有烦人的行。 您始终可以在to_csv方法中设置列和索引名称。

您的输出将如下所示:

 key1,a key2,b key3,c 

如果您想将这些键作为列的名称,只需使用默认的“orient”参数即“列”即可,如您可以在文档链接中查看的那样。