How to: Coordinate DictReader and Reader for CSV

Tim Chase python.list at tim.thechases.com
Mon Nov 21 13:36:14 EST 2011


On 11/21/11 09:16, ray wrote:
> Is there a way to capture the keys outside of the for loop so
> when the for loop is entered, only data is extracted?

I frequently do this for things like tweaking headers (stripping 
space, normalizing case, etc because clients love to send us 
messy data):

   def norm_header(h):
     return h.strip().upper()
   def norm_item(i):
     return i.strip()

   f = file("example.csv", "rb")
   try:
     r = csv.reader(f)
     headers = r.next()
     header_map = dict(
       (norm_header(h), i)
       for i, h in enumerate(headers)
       )
     for row in r:
       item = lambda h: norm_item(row[header_map[norm_header(h)]])
       value1 = item("Item1")
       value2 = item("ITEM3")
       ...
   finally:
     f.close()

Should work in 2.x, possibly in 3.x (though you might need to 
change from "headers = r.next()" to "headers = next(r)")

-tkc





More information about the Python-list mailing list