本文介绍了使用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:

它也可以在writerows上运行,在内部,它只是重复调用writerow.

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

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

09-05 02:25