How to: Coordinate DictReader and Reader for CSV

ray ray at aarden.us
Mon Nov 21 10:16:15 EST 2011


On Nov 21, 7:59 am, Neil Cerutti <ne... at norwich.edu> wrote:
> On 2011-11-21, ray <r... at aarden.us> wrote:
>
> > I am trying to get the data from a CSV file into variables.  I have
> > used DictReader to get the field names and I can report them.  When I
> > attempt to look at the data, every row shows the combination of
> > fieldname:data.  How do I get the data out?

> > linelist=open( "C:/Users/thisuser/Documents/Projects/Bootstrap Plan
> > Design Tool/Sandbox/line_list_r0a.csv", "rb" )
> > csvDictReader=csv.DictReader( linelist, dialect='excel' )
> > for data in csvReader:
> >         print data[0]
> >         print data[1]
> >         print data[2]
> >         print data[3]
> > linelist.close()
>
> The elements yielded by a DictReader iterator are dictionaries,
> and the keys are the headings of the csv file. So replace those
> integers with strings representing the headings of your file.
>
> If the headings are actually those numbers, you want:
>
> [...]
>     print data['0']
>     print data['1']
>     print data['2']
>     print data['3']
>     print data['4']
> [...]
>
> --
> Neil Cerutti
>   "This room is an illusion and is a trap devisut by Satan.  Go
> ahead and dauntlessly!  Make rapid progres!"
>   --Ghosts 'n Goblins

Neil,

Thank you for your efforts.

When I use the 0, 1, etc. in the data[x] slot, I get some data.  When
I put a string in, I get an error stating:
TypeError: list indices must be integers, not str

But your suggestion has helped my better understand my problem. The
output is first a list of the keys and then the associated data.  The
difficulty is that I want to pass the data to another function will I
am in the 'for' loop.  But the first data out is keys and that is not
the data I want to send to the other function.  Is there a way to
capture the keys outside of the for loop so when the for loop is
entered, only data is extracted?

Thanks,
ray




More information about the Python-list mailing list