Reading a CSV file into a list of dictionaries
Robert Kern
rkern at ucsd.edu
Mon Jun 6 13:28:00 EDT 2005
RFQ wrote:
> Hi, I'm struggling here to do the following with any success:
>
> I have a comma delimited file where each line in the file is something
> like:
>
> PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,...
>
> So each line is intended to be: key1,value1,key2,value2,key3,value3...
> and each line is to be variable in length (although it will have to be
> an even number of records so that each key has a value).
>
> I want to read in this csv file and parse it into a list of
> dictionaries. So each record in the list is a dictionary:
>
> {"PNumber":"3056","Contractor":"XYZ Contracting", ... }
>
> I have no problem reading in the CSV file to a list and splitting each
> line in the file into its comma separated values. But I can't figure
> out how to parse each resulting list into a dictionary.
First, don't process the CSV stuff yourself. Use the csv module.
In [9]:import csv
In [10]:f = open('foo.csv')
In [11]:cr = csv.reader(f)
In [12]:for row in cr:
....: print dict(zip(row[::2], row[1::2]))
....:
{'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ
Contracting'}
{'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ
Contracting'}
[etc.]
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list