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

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

问题描述

我有一本字典:

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

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

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

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

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

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.

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

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.

推荐答案

DictWriter 不符合您的预期.

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

要回读:

with open('dict.csv') 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

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

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