0

Assuming I have a pandas DF as follows:

mydf=pd.DataFrame([{'sectionId':'f0910b98','xml':'<p/p>'},{'sectionId':'f0345b98','xml':'<a/a>'}])
mydf.set_index('sectionId', inplace=True)

enter image description here

I would like to get a dicctionary out of it as follwos:

{'f0910b98':'<p/p>', 'f0345b98':'<a/a>'}

I tried the following:

mydf.to_dict()
mydf.to_dict('records')

And it is not what I am looking for.

I am looking for the correct way to use to_dict()

Note: I know I can get the two columns into two lists and pack them in a dict like in:

mydict = dict(zip(mydf.sectionId, mydf.xml))

but I am looking for a pandas straight direct method (if there is one)

2
  • 2
    I would have gone with dict(zip) too... Commented May 19, 2021 at 14:54
  • None of the orient options do what you want to accomplish with your data in its current form. The dict(zip( approach is commonly used to meet your requirements. Commented May 19, 2021 at 15:29

1 Answer 1

1

You could transpose your dataframe and then to_dict it and select the first item (the xml now-index).

mydf.T.to_dict(orient='records')[0]

returns

{'f0910b98': '<p/p>', 'f0345b98': '<a/a>'}
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.