问题描述
我编写了一个函数,该函数使用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:
它也可以在writerows
上运行,在内部,它只是重复调用writerow
.
It also works on writerows
, which, internally, just calls writerow
repeatedly.
这篇关于使用DictWriter编写字典键的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!