Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #16043
| Date | 2011-11-21 12:36 -0600 |
|---|---|
| From | Tim Chase <python.list@tim.thechases.com> |
| Subject | Re: How to: Coordinate DictReader and Reader for CSV |
| References | <2012e1cb-5913-4f39-b102-038a1c95a483@gi1g2000vbb.googlegroups.com> <9iv3q7F1t5U1@mid.individual.net> <04bc73a1-1408-4626-991f-fad94933cb5f@p2g2000vbj.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2928.1321902366.27778.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
How to: Coordinate DictReader and Reader for CSV ray <ray@aarden.us> - 2011-11-21 05:18 -0800
Re: How to: Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 13:59 +0000
Re: How to: Coordinate DictReader and Reader for CSV ray <ray@aarden.us> - 2011-11-21 07:16 -0800
Re: How to: Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 15:41 +0000
Re: How to: Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 15:43 +0000
Re: How to: Coordinate DictReader and Reader for CSV Tim Chase <python.list@tim.thechases.com> - 2011-11-21 12:36 -0600
csiph-web