Python itertools.groupby multiple values
<p>I have records returned from a database that look like this:</p>

<pre><code>region       month_taken         total_att num_classes
Colorado    2013-01-01 00:00:00.000 78485   4648
Colorado    2013-02-01 00:00:00.000 71769   4162
Midwest     2013-01-01 00:00:00.000 110508  7101
Midwest     2013-02-01 00:00:00.000 103545  6410
</code></pre>

<p>I'm attempting to get them into lists as so:</p>

<p>Total_att:</p>

<pre><code>[{"data": [78485, 71769], "name": "Colorado"}, {"data": [110508, 103545], "name": "Midwest"}]
</code></pre>

<p>num_classes:</p>

<pre><code>[{"data": [4648, 4162], "name": "Colorado"}, {"data": [7101, 6410], "name": "Midwest"}]
</code></pre>

<p>I discovered itertools.groupby which does what I want, but I'm having difficulty doing it with more than one list of values (for lack of a better term).</p>

<pre><code>totalResults = []            
for key, location in groupby(rows, lambda k: k[0]):
    totalRow = dict()
    totalRow['name'] = key
    totalRow['data'] = [x[2] for x in location]
    totalResults.append(totalRow)
</code></pre>

<p>Great, that gets me my total_att list, but then I do an entire additional groupby loop to create the "num_classes" list, which seems ridiculous. I saw this in the docs, but honestly I'm not quite sure what it means or how to handle my problem if I converted it to a list: </p>

<p><code>The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:</code></p>

<p>So, how can I create my lists without doing multiple for key, location in groupby(rows, lambda k: k[0]):? </p>

<p>I hope that is clear, but am happy to provide more information as necessary.</p>
