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

查看:231
本文介绍了将字典写入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文件),加载设置应从文件中读取并更新textctrl和复选框.

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不能按您期望的方式工作.

The DictWriter doesn't work the way you expect.

# For python 2, skip the "newline" argument: open('dict.csv','w")
with open('dict.csv', 'w', newline="") 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天全站免登陆