Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flipping a python dictionary obtained from python dataframe

I have a pandas dataframe and it looks like so:

person    weight    height    skill
kate       160       200       100
john       170       150       70

I have set the person column as the index of my python dataframe. And then i turned it into a dictionary using the .to_dict() method. this gives the following dictionary:

{'weight': {'kate': '160', 'john': '170'},
'height': {'kate': '200', 'john': '150'},
'skill': {'kate': '100', 'john': '70'},
             

I need to change the around so that the dictionary is per person, but i dont know if its possible to do in python. What i need my dictionary to look like is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'Kate: { weight': '160', 'height': '200', 'skill': '100'},
 'John': {'weight': '170', 'height': '150', 'skill': '70'}}

Is it possible to do this?

>Solution :

You can set person as the index and use to_dict with orient arg set to index.

df.set_index('person').to_dict('index')

# {'kate': {'weight': 160, 'height': 200, 'skill': 100},
#  'john': {'weight': 170, 'height': 150, 'skill': 70}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading