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

Peter Otten __peter__ at web.de
Thu Jul 5 14:06:16 EDT 2007


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




More information about the Python-list mailing list