2010-07-08 58 views
9

我写的连载词典作为使用csv模块CSV文件列表的功能,使用如下代码:使用DictWriter写一本字典的键的子集

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

不过,我有时候想只向文件写出每个字典密钥的一个子集。如果我通过为fieldnames每个字典具有键的子集,我得到的错误:

"dict contains fields not in fieldnames" 

我怎样才能让这个DictRows会写只是字段的子集我指定CSV,忽略那些字段中的字段而不是字段名中的字段?

回答

33

最简单,最直接的方法是通过extrasaction='ignore'当你初始化DictWriter例如,如记录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反复。

+1

未找到字典键的选项restval与extrasaction ='ignore'特别有用。 – Gregor 2013-01-17 11:04:20

1

更改为您的代码:

忘记Dictwriter,使用普通的作家。

然后循环在你的类型的字典列表:

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

使用d.get(fieldname, "")而不是d[fieldname]如果你不想要一个例外,如果在dfieldname没有条目。

注意匿名downvoters:这是做什么亚历克斯的解决方案是在引擎盖下(见Lib/csv.py)并做得更好一点... csv.py调用一个函数来获取列表中的每一行,并且该功能的内容是

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

-1;当DictWriter提供了一个方便的参数来自动解决问题时,没有理由这样做,如Alex的回答中所述。 – 2018-01-04 22:13:55