Where is the syntax for the dict() constructor ?!

Thomas Jollans thomas at jollans.com
Thu Jul 5 20:30:10 CEST 2007


On Thursday 05 July 2007, Captain Poutine wrote:
> Peter Otten wrote:
> > Neil Cerutti wrote:
> >> On 2007-07-05, Captain Poutine <captainpoutine at gmail.com> wrote:
> >>> I'm simply trying to read a CSV into a dictionary.
> >>>
> >>> (if it matters, it's ZIP codes and time zones, i.e.,
> >>> 35983,CT
> >>> 39161,CT
> >>> 47240,EST
> >>>
> >>>
> >>>
> >>> Apparently the way to do this is:
> >>>
> >>> import csv
> >>>
> >>> dictZipZones = {}
> >>>
> >>> reader = csv.reader(open("some.csv", "rb"))
> >>> for row in reader:
> >>>      # Add the row to the dictionary
> >>
> >> In addition to Chris's answer, the csv module can read and write
> >> dictionaries directly. Look up csv.DictReader and csv.DictWriter.
> >
> > DictReader gives one dict per row, with field names as keys. The OP is
> > more likely to want
> >
> > dict(csv.reader(open("some.csv", "rb")))
> >
> > which produces a dict that maps ZIP codes to time zones.
> >
> > Peter
>
> Thanks Peter, that basically works, even if I don't understand it.
>
> What does "rb" mean? (read binary?)
> Why are the keys turned into strings (they are not quoted in the .csv
> file)?

"rb" is read, in binary mode. On DOS and derivatives this prevents intentional 
file corruption when reading. (for ASCII files, omitting the b might be 
desirable...)

Think of csv.reader as a fancy variant of the following: (fancy in that it 
supports things like non-comma separators and comma escaping)

def CSVReader(file):
  for line in file:
    yield line.split(',')

-- 
      Regards,                       Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key <http://hackerkey.com/>:
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/python-list/attachments/20070705/527a6312/attachment.pgp>


More information about the Python-list mailing list