sabbahillel
sabbahillel

Reputation: 4425

Write a partial row with csv.DictWriter?

I have a CSV file with a group of inputs.

Example:

A B C D

I want to analyze the results and output a CSV file for each row such as:

B C

The DictReader builds the full dictionary with the keys 'A' 'B' 'C' 'D' in it as it should.
The DictWriter sets up the fields as it is supposed to.

However, when I attempt the send the data to the DictWriter, I get the error message:

ValueError: dict contains fields not in fieldnames: A D

Must I delete the value entries by hand from the dictionary or is there a simple automatic way to set this up?

I am using Python 2.6.6 and am unable to update to a later version.

Upvotes: 1

Views: 916

Answers (1)

martineau
martineau

Reputation: 123501

Yes, there's a simple way to do it. When you create the csv.DictWriter instance being used, just pass it the keyword argument extrasaction='ignore'—the default value for it is 'raise', which is the cause of the ValueError exception you're getting when you pass it a dictionary with keys not specified in the fieldnames parameter.

BTW, reading the relevant documentation before asking SO questions is often a worthwhile endeavor—and can often provide answers without further delay.

Upvotes: 2

Related Questions