Monday 15 February 2010

Python 2.6 How can I reiterate over a DictReader object that took in a list object? -



Python 2.6 How can I reiterate over a DictReader object that took in a list object? -

python 2.6(necessary job)

import csv list = ['apple,whiskey,turtle', 'orange,gin,wolf', 'banana,vodka,sparrow'] fieldnames = ['fruit', 'spirit', 'animal'] reader = csv.dictreader(list,fieldnames= fieldnames) row in reader: print row['fruit'] row in reader: print row['fruit']

i have code generates uniform list of items per row, making list object. ease of utilize used csv module's dictreader step through rows , calculations need when seek iterate sec time, no output. suspect end of list beingness treated eof unable 'seek' origin of list iteration again.

any suggestions on can do? perhaps there improve way using csv, seemed convenient.

new code

import csv list = ['apple,"whiskey,rum",turtle', 'orange,gin,wolf', 'banana,vodka,sparrow'] processed = [] fieldnames = ['fruit', 'spirit', 'animal'] reader = csv.dictreader(list,fieldnames= fieldnames, quoatechar = '"') row in reader: processed.append(row) print row row in processed: print row['fruit'] row in processed: print row['spirit']

@jonrsharpe suggested placing rows of reader list. works had in mind. give thanks everyone.

you're indeed right iterating on rows 1 time dictreader provides. options are:

create new dictreader , iterate 1 time again (seems wasteful) iterate on rows 1 time , perform computations want perform iterate on rows once, store info in info construction , iterate on info construction many times wish.

also, if have list , field names don't need dictreader same thing. if know info relatively straightforward (no comma's within info illustration , same number of items) can do:

merged = [zip(fieldnames, row.split(",")) row in my_list] print merged

python list csv

No comments:

Post a Comment