[Tutor] How to output dictionary data to CSV file
Paradox
paradox at pobox.com
Tue Apr 28 11:00:34 CEST 2015
How rude of me, I neglected to note I am using Python 3.4.3.
On 04/28/2015 04:51 PM, Paradox wrote:
> I have some data structured like this:
>
> {'B002':'NRP 2014','B003':'HBB 2015'}
>
> Basically account numbers and project names, each account number has a
> project name. I represent it in a dictionary because that seemed the
> best way to keep the account numbers and project names together. I
> want to save that information to a file, CSV seemed the easiest format
> (though I am open to suggestions if there is a better way!). I
> expected I could write a function that would create a CSV file that
> looks like this:
>
> B002,NRP 2014
> B003,HBB 2015
>
> I thought the DictWriter method of the CSV module should do the trick
> so wrote this:
>
> def write_fqas(fqa_csv,fqa_dict):
> with open('fqa_csv','w') as csvfile:
> writer = csv.DictWriter(csvfile,fieldnames=['FQA','Description']
> writer.writerows(fqa_dict)
>
> This didn't yield the results I was looking for, instead it raises
>
> ValueError: dict contains fields not in fieldnames: 'B', '0', '0', '2'
>
> It seems to be parsing through the key of the first item in the
> dictionary rather than simply saving it to the CSV file as the first
> field on a line (like I expected). Obviously there is something about
> how csv.DictWriter works that I don't understand.
>
> Any assistance is appreciated.
>
> thomas
> ==============================
> Thomas C. Hicks, MD, MPH
> Training Manager, Gansu Gateway
> Lanzhou, Gansu, PR China
More information about the Tutor
mailing list