On Thursday 05 July 2007, Captain Poutine wrote: > Peter Otten wrote: > > Neil Cerutti wrote: > >> On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> 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
signature.asc
Description: This is a digitally signed message part.
-- http://mail.python.org/mailman/listinfo/python-list