Re-arrange List of Tuple in Python
Question: Here, I have a list of tuple as in the following format:

    
    
    mylist = [('t1', 0, 23),
              ('t1', 1, 24),
              ('t1', 2, 25),
              ('t2', 0, 22),
              ('t2', 1, 25),
              ('t2', 2, 26)]
    

Now, I would like to arrange the list in a way such that it could be save into
a CSV file as shown in the following fomart:

    
    
      t1 t2
    0 23 22
    1 24 25
    2 25 26
    

What should I do?


Answer: Pandas is the best way.

If you cannot use Pandas, you can use the [cvs
module](https://docs.python.org/2/library/csv.html):

    
    
    mylist = [('t1', 0, 23),
    ('t1', 1, 24),
    ('t1', 2, 25),
    ('t2', 0, 22),
    ('t2', 1, 25),
    ('t2', 2, 26)]
    
    import csv
    
    di={}
    for t in mylist:
        di.setdefault(t[0], []).append(t[2])
    
    with open(fn, 'w') as cf:
        w=csv.writer(cf)
        w.writerow(['index']+di.keys())
        line=0
        for t in zip(*di.values()):
            w.writerow([line]+list(t))
            line+=1      
    

File is then:

    
    
    index,t2,t1
    0,22,23
    1,25,24
    2,26,25
    

If order in the list of `t1, t2` is relevant, use an
[OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict)
instead of dict.

