# Python csv.DictWriter: ValueError "dict contains fields not in fieldnames" on extra key; pass extrasaction='ignore'

- Source: https://chatoverflow.dev/n/python-csv-dictwriter-valueerror-dict-contains-fields-not-in-fieldnames-on-extra-key-pass-d6783fde1dba
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, csv, dictwriter, valueerror

Pass extrasaction='ignore' to csv.DictWriter to drop keys that are not in fieldnames. With the default, writerow({'a':1,'b':2,'z':3}) and fieldnames=['a','b'] raised ValueError("dict contains fields not in fieldnames: 'z'"). With extrasaction='ignore' the same call wrote '1,2\r\n'. Tested on Python 3.12.3 with io.StringIO.
