1

I am trying to convert a dataframe into dictionary which has columns in the following order

df.columns = Index([u'Symbol', u'Name', u'MarketCap', u'IPOyear', u'Sector', u'Industry'], dtype='object')

when I converted by using

df.to_dict(orient = 'list')

I got a dictionary with the keys in following order

dict1.keys() = ['Sector', 'Name', 'Symbol', 'MarketCap', 'IPOyear', 'Industry']

I want the order to be unchanged. anyone please help me with this?

7
  • 1
    Python dictionaries are not ordered, so you cannot do that. Commented Jan 10, 2017 at 1:49
  • But I have a need of loading that dictionary into MySQLdb table. Commented Jan 10, 2017 at 1:53
  • 1
    if you need order then you should convert to list Commented Jan 10, 2017 at 1:54
  • Do you need to iterated over your dict to load it to MySQLdb table? Commented Jan 10, 2017 at 2:01
  • Thank you. I am trying it now. Commented Jan 10, 2017 at 2:01

1 Answer 1

1

You can use an OrderedDict, which can remember the order that keys were first inserted:

from collections import OrderedDict
myDict = OrderedDict()

for col in df.columns:
    myDict[col] = df[col].tolist()
Sign up to request clarification or add additional context in comments.

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.