JFerro
JFerro

Reputation: 3443

Convert pandas dataframe into dictionary with keys one column and values the other

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)

Upvotes: 0

Views: 64

Answers (1)

mids
mids

Reputation: 366

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>'}

Upvotes: 1

Related Questions