0

I have a Pandas data frame & I need to convert it to list of dictionaries but when I use df.to_dict(), i'm not getting what I expected.

Data Frame:

    Name  Class School
0   Alex      4    SVN
1  Julie      4    MSM

After using df.to_dict(),

{'Name': {0: 'Alex', 1: 'Julie'}, 'Class': {0: 4, 1: 4}, 'School': {0: 'SVN', 1: 'MSM'}}

But, I need something like below,

[{'Name':'Alex', 'Class': 4, 'School':'SVN'}, {'Name':'Julie', 'Class': 5, 'School':'MSM'}]

How can I do this? What's the efficient way of doing this?

1

1 Answer 1

2

Try this: df.T.to_dict().values() instead of df.to_dict():

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.