Reading a CSV file into a list of dictionaries
Peter Otten
__peter__ at web.de
Mon Jun 6 13:34:24 EDT 2005
RFQ wrote:
> 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", ... }
>>> row
['PNumber', '3056', 'Contractor', 'XYZ Contracting', 'Architect', 'ABC']
>>> dict(zip(row[::2], row[1::2]))
{'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'}
A bit more elegant:
>>> irow = iter(row)
>>> dict(zip(irow, irow))
{'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'}
Peter
More information about the Python-list
mailing list