csv dictreader

Mike Driscoll kyosohma at gmail.com
Wed Mar 19 20:55:21 CET 2008


On Mar 19, 1:55 pm, brnstrmrs <brnstr... at gmail.com> wrote:
> On Mar 19, 2:32 pm, Mike Driscoll <kyoso... at gmail.com> wrote:
>
>
>
> > On Mar 19, 1:06 pm, brnstrmrs <brnstr... at gmail.com> wrote:
>
> > > I am trying to use the dictionary reader to import the data from a csv
> > > file and create a dictnary from it but just can't seem to figure it
> > > out.
>
> > > Here is my code:
>
> > > >>>import csv
> > > >>>reader = csv.DictReader(open('table.csv'))
> > > >>>for row in reader:
> > > >>>print row
>
> > > my csv files looks like this:
>
> > > Bytecode,Element
> > > \x00\x00,0000
> > > \x01\x00,0001
> > > ....
> > > \x09\x00,0009
>
> > > My output shows:
> > > {'Bytecode': '\\x00\\x00', 'Element': '0000'}
> > > {'Bytecode': '\\x01\\x00', 'Element': '0001'}
> > > ...
> > > {'Bytecode': '\\x09\\x00', 'Element': '0009'}
>
> > > 1. how can I get access to this directory
>
> > What do you mean? You can get each element in the dict by doing this:
>
> > for row in reader:
> >     print row['Bytecode']
> >     print row['Element']
>
> > > 2. why does the values come with two backslashs infront of the "x"
>
> > The double back slash is for escaping purposes, I think. If you print
> > this: '\\x09\\x00'
> > you'll get this:  \x09\x00
>
> > Mike
>
> Thanks.  It works for the Bytecode but when I do print row['Element']
> I get a error message    print row['Element'] KeyError: 'Element'

That's weird. Since I only had your output, I did the following:

<code>

reader = [ {'Bytecode': '\\x00\\x00', 'Element': '0000'},{'Bytecode':
'\\x01\\x00', 'Element': '0001'} ]

for x in reader:
	print x['Element']
	print x['Bytecode']


0000
\x00\x00
0001
\x01\x00

</code>

I must be missing something...

Mike



More information about the Python-list mailing list