<br><div class="gmail_quote"><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
I have noticed this odd behaviour in the CSV DictReader Class, and at a loss to understand/ get around it.<br>
<br>
The aim is to read in a CSV file, and then iterate over the lines. The problem (seems) to be that once you have iterated over it once, you can't do it again.<br>
<br></blockquote><div>This is expected behavior. See below from the Python docs:<br>
<br>
<a href="http://docs.python.org/glossary.html#term-iterator">http://docs.python.org/glossary.html#term-iterator</a><br>
<a href="http://docs.python.org/library/stdtypes.html#typeiter">http://docs.python.org/library/stdtypes.html#typeiter</a><br>
<br>
If you'd like to make multiple passes over the lines from your CSV,
store them in a variable when you first read them in and then loop over
that variable instead. <br>
<br>One approach (though it may not be the best if you're dealing with huge quantities of data):<br><br>reader = csv.DictReader(open(fname, 'r'), delimiter = ',', quotechar = '"')<br>data = [row for row in reader]<br>
# now you can make multiple passes over the dictionaries stored in "data"<br> </div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
I don't know if this is me (and it may well be) but it seems to be a recurrent issue, and means that a csv.DictReader doesn't behave in the same way as a normal dict object.<br></blockquote><div> </div><div>Correct. It's not supposed to behave like a normal dict. It behaves like a reader object. See the python docs:<br>
<br>"Create an object which operates like a regular reader but maps the information
read into a dict whose keys are given by the optional <em>fieldnames</em> parameter."<br><a href="http://docs.python.org/library/csv.html#reader-objects">http://docs.python.org/library/csv.html#reader-objects</a><br>
<br>HTH,<br>Serdar<br></div></div>