Merge list concating unique values as comma seperated retaining original order from csv
<p>Here is my data:</p>

<p>data.csv</p>

<pre><code>id,fname,lname,education,gradyear,attributes
1,john,smith,mit,2003,qa
1,john,smith,harvard,207,admin
1,john,smith,ft,212,master
2,john,doe,htw,2000,dev
</code></pre>

<p>Here is the code:</p>

<pre><code>from itertools import groupby
import csv
import pprint


t = csv.reader(open('data.csv'))
t = list(t)


def join_rows(rows):
    return [(e[0] if i &lt; 3 else ','.join(e)) for (i, e) in enumerate(zip(*rows))]



for name, rows in groupby(sorted(t), lambda x:x[0]):
    print join_rows(rows)
</code></pre>

<p>It works, but while merging it doest not retain original order, instead it works from concating last to first</p>

<p>Output is:</p>

<pre><code>['1', 'john', 'smith', 'ft,harvard,mit', '212,207,2003', 'master,admin,qa']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
</code></pre>

<p>Instead of:</p>

<pre><code>['1', 'john', 'smith', 'mit,harvard,ft', '2003,207,212', 'qa,admin,master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
</code></pre>

<p>as it is listed in the CSV file (original order)</p>

<p>My approach to fix this would be to rerun though values and try to reverse it. Is there any cleverer approach? </p>

<p>The problem is sorting, which is not required. Change as:</p>

<pre><code>groupby(t, lambda x:x[0])
</code></pre>

python