[Tutor] How to output dictionary data to CSV file
Peter Otten
__peter__ at web.de
Tue Apr 28 11:30:54 CEST 2015
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.
DictWriter expects a sequence of dicts where the keys are the column names.
Example:
>>> import csv
>>> import sys
>>> data = [
... {"FQA": "B002", "Description": "NRP 2014"},
... {"FQA": "B003", "Description": "HBB 2015"},
... ]
>>> writer = csv.DictWriter(sys.stdout, fieldnames=["FQA", "Description"])
>>> writer.writerows(data)
B002,NRP 2014
B003,HBB 2015
As you want to write both keys and values as a column you can pass the dict
items() to a normal csv.writer:
>>> data = {'B002':'NRP 2014','B003':'HBB 2015'}
>>> writer = csv.writer(sys.stdout)
>>> writer.writerows(data.items())
B002,NRP 2014
B003,HBB 2015
> How rude of me, I neglected to note I am using Python 3.4.3.
And now you're top-posting to make it even worse ;)
More information about the Tutor
mailing list