Python:将字典写入一个csv文件,每行一个“key:value” [英] Python: Writing a dictionary to a csv file with one line for every 'key: value'

查看:3141
本文介绍了Python:将字典写入一个csv文件,每行一个“key:value”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典:



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()
pre>

但现在我在一行中有所有键,而在下一行中有所有值。



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



只是为了解释我的代码,字典包含值和boct从textctrls和复选框(使用wxpython)。我要添加保存设置和加载设置按钮。
保存设置应该以所提到的方式将字典写入文件(为了使用户更容易直接编辑csv文件),加载设置应该从文件中读取并更新textctrls和复选框。

解决方案

DictWriter 无法按照您的预期工作。

  with open('dict.csv','wb')as csv_file:
writer = csv.writer(csv_file)
键,mydict.items()中的值:
writer.writerow([key,value])


b $ b

要读回它:

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

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


I've got a dictionary:

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

I want to write the data to a file dict.csv, in this style:

key1: value_a
key2: value_b
key3: value_c

I wrote:

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

But now I have all keys in one row and all values in the next row..

When I manage to write a file like this, I also want to read it back to a new dictionary.

Just to explain my code, the dictionary contains values and bools from textctrls and checkboxes (using wxpython). I want to add "Save settings" and "Load settings" buttons. Save settings should write the dictionary to the file in the mentioned way (to make it easier for the user to edit the csv file directly), load settings should read from the file and update the textctrls and checkboxes.

解决方案

The DictWriter doesn't work the way you expect.

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

To read it back:

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

which is quite compact, but it assumes you don't need to do any type conversion when reading

这篇关于Python:将字典写入一个csv文件,每行一个“key:value”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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