使用DictWriter编写字典键的子集

2024-06-28 19:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是,有时我只想将每个字典的键的一个子集写入一个文件。如果我将每个字典的键的子集作为fieldnames传递,就会得到错误:

"dict contains fields not in fieldnames"

我怎样才能使DictRows只写我指定给CSV的字段的一个子集,而忽略那些在字典中但不在字段名中的字段?


Tags: 模块文件csv函数代码列表data字典
2条回答

代码更改:

忘记听写器,用普通的书写器。

然后在你的口述清单上循环:

for d in dictrows:
    ordinary_writer.writerow([d[fieldname] for fieldname in fieldnames])

如果不希望在d中没有用于fieldname的条目时出现异常,请使用d.get(fieldname, ""),而不是d[fieldname]

给匿名落选者的注意:这是在幕后做亚历克斯的解决方案(见Lib/csv.py),做得更好一点。。。py调用一个函数来获取列表中的每一行,该函数的核心是

return [rowdict.get(key, self.restval) for key in self.fieldnames]

最简单和最直接的方法是在初始化DictWriter实例时传递extrasaction='ignore',如文档所述here

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

相关问题 更多 >