使用DictWriter编写字典键的子集 [英] Using DictWriter to write a subset of a dictionary's keys

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

问题描述

我编写了一个函数,该函数使用csv模块将字典列表序列化为CSV文件,其代码如下:

I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:

data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)

但是,有时我只想将每个字典键的一个子集写到文件中.如果我以fieldnames的形式传递每个字典具有的键的子集,则会收到错误消息:

However, I sometimes want to write out to a file only a subset of each dictionary's keys. If I pass as 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',如

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

如果字典传递给 writerow()方法包含的密钥不 在字段名称中找到,可选 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.

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

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