使用 DictWriter 写入字典键的子集
我编写了一个函数,使用 csv
模块将字典列表序列化为 CSV 文件,代码如下:
data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)
但是,有时我只想将每个字典键的子集写入文件。如果我将每个字典具有的键的子集作为 fieldnames
传递,则会收到错误:
"dict contains fields not in fieldnames"
如何才能使 DictRows 只将我指定到 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)
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"
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单、最直接的方法是在初始化
DictWriter
实例时传递extrasaction='ignore'
,如文档所述 此处:它也适用于 writerows,它在内部只是重复调用 writerows。
Simplest and most direct approach is to pass
extrasaction='ignore'
when you initialize yourDictWriter
instance, as documented here:It also works on
writerows
, which, internally, just callswriterow
repeatedly.更改代码:
忘记 Dictwriter,使用普通 writer。
然后循环遍历您的字典列表:
如果您不希望出现异常,请使用
d.get(fieldname, "")
而不是d[fieldname]
d
中的条目为fieldname
。匿名反对者请注意:这正在执行 Alex 的解决方案在幕后所做的事情(请参阅 Lib/csv.py),并且做得更好一点...... csv.py 调用一个函数来获取列表中的每一行,并且内部结构该函数的
Changes to your code:
Forget Dictwriter, use ordinary writer.
Then loop over your list of dicts:
Use
d.get(fieldname, "")
instead ofd[fieldname]
if you don't want an exception if there is no entry ind
for afieldname
.Note to anonymous downvoters: This is doing what Alex's solution is doing under the hood (see Lib/csv.py) and doing it a bit better ... csv.py calls a function to get each row in a list, and the guts of that function is