在Python中使用DictWriter来编写字典键的子集 [英] using DictWriter in Python to write a subset of a dictionary's keys

查看:2203
本文介绍了在Python中使用DictWriter来编写字典键的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数,使用CSV模块将字典列表序列化为CSV文件。我有时想要写一个文件只有每个字典的键的一个子集。我使用以下代码:

I wrote a function that serializes a list of dictionaries as a CSV file using the CSV module. I sometimes want to write out to a file only a subset of each dictionary's keys however. I use the following code:

def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
          lineterminator='\n'):
out_f = open(filename, 'w')

# Write out header
header = delimiter.join(fieldnames) + lineterminator
out_f.write(header)

# Write out dictionary
data = csv.DictWriter(out_f, fieldnames,
          delimiter=delimiter,
          lineterminator=lineterminator)
data.writerows(dictrows)
out_f.close()

如果我传入fieldnames每个字典的键的一个子集,我得到错误:

If I pass in "fieldnames" a subset of the keys that each dictionary has, I get the error:

"dict contains fields not in fieldnames"

如何使DictRows只写一个字段的子集指定为CSV,忽略字典中但不在字段名中的字段。

How can I make it so that DictRows will write just a subset of the fields I specify to CSV, ignoring those fields that are in the dictionary but not in fieldnames?

感谢。

推荐答案

当您初始化 DictWriter 时,最简单和最直接的方法是传递 extrasaction ='ignore' $ c>实例,如此处所述:

Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:


如果传递给
writerow()方法的字典包含键不是
在fieldnames中找到,可选的
extrasaction参数指示采取什么
操作。如果设置为
'raise',则会引发一个 ValueError 。如果
设置为'ignore',则忽略
中的额外值。

If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.

它也可以在 writerows 下工作,在内部只需调用 writerow 反复。

It also works on writerows, which, internally, just calls writerow repeatedly.

这篇关于在Python中使用DictWriter来编写字典键的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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