0

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.

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help, it works well with my issue
1

Try using OrderedDict instead of dictionary. OrderedDict is part of collections module.

Docs: link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.