2010-07-08 22 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