python preserving output csv file column order
<p>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:</p>

<pre><code>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')
</code></pre>

<p>the original csv file is like:</p>

<pre><code>a,c,b
1,9,5
2,10,6
3,11,7
4,12,8
</code></pre>

<p>while I'd like to fixed the order of the column like the output:</p>

<pre><code>a,b,c
1,5,9
2,6,10
3,7,11
4,8,12
</code></pre>

<p>and the answers I found are mostly related to <code>pandas</code>, I wonder if we can solve this in another way.</p>

<p>Any help is appreciated, thank you.</p>

<p>Instead of <code>dct={}</code> just do this:</p>

<pre><code>from collections import OrderedDict
dct = OrderedDict()
</code></pre>

<p>The keys will be ordered in the same order you define them.</p>

<p>Comparative test:</p>

<pre><code>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
</code></pre>

<p>result:</p>

<pre><code>['a', 'c', 'b']
['a', 'b', 'c']
</code></pre>

python csv order