python preserving output csv file column order
Question: The issue is common, when I import a csv file and process it and finally
output it, the order of column in the output csv file may be different from
the original one,for instance:

    
    
    dct={}
    dct['a']=[1,2,3,4]
    dct['b']=[5,6,7,8]
    dct['c']=[9,10,11,12]
    
    header = dct.keys()
    rows=pd.DataFrame(dct).to_dict('records')
    
    with open('outTest.csv', 'wb') as f:
        f.write(','.join(header))
        f.write('\n')
        for data in rows:
            f.write(",".join(str(data[h]) for h in header))
            f.write('\n')
    

the original csv file is like:

    
    
    a,c,b
    1,9,5
    2,10,6
    3,11,7
    4,12,8
    

while I'd like to fixed the order of the column like the output:

    
    
    a,b,c
    1,5,9
    2,6,10
    3,7,11
    4,8,12
    

and the answers I found are mostly related to `pandas`, I wonder if we can
solve this in another way.

Any help is appreciated, thank you.


Answer: Instead of `dct={}` just do this:

    
    
    from collections import OrderedDict
    dct = OrderedDict()
    

The keys will be ordered in the same order you define them.

Comparative test:

    
    
    from collections import OrderedDict
    dct = OrderedDict()
    dct['a']=[1,2,3,4]
    dct['b']=[5,6,7,8]
    dct['c']=[9,10,11,12]
    
    stddct = dict(dct)  # create a standard dictionary
    
    print(stddct.keys())  # "wrong" order
    print(dct.keys())     # deterministic order
    

result:

    
    
    ['a', 'c', 'b']
    ['a', 'b', 'c']
    

