csv dictreader

brnstrmrs brnstrmrs at gmail.com
Wed Mar 19 14:55:18 EDT 2008


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'



More information about the Python-list mailing list