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

How to put every line of a excel table into a python dictionary?

Just beginning with python and working on a small project.
Trying to figure out to get a list of dictionarys for every line in a Excel file.

For example:

first_name last_name age
Peter Johnsen 42
Mark Conner 32
Susanna Rock 36

Into:

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

[
{'first_name' : 'Peter' , 'last_name' : 'Johnsen' , 'age' : '42'} ,
{'first_name' : 'Mark' , 'last_name' : 'Conner' , 'age' : '32'} ,
{'first_name' : 'Susanna' , 'last_name' : 'Rock' , 'age' : '36'} ,
]

I figured out to get a dictionary for my excel-file but that way I get a dictionary for every column.

import pandas as pd

data = 'person.xlsx'

df = pd.read_excel(data)

df_dict = df.to_dict()

print(df_dict)
{
'first_name' : {0: 'Peter' , 1 : 'Mark' , 2 : 'Susanna'} ,
'last_name' : {0: 'Johnsen' , 1 : 'Conner' , 2 : 'Rock'} ,
'age' : {0: '42' , 1 : '32' , 2 : '36'} ,
}

How can I transform the dictionary or is there a way to get a dictionary right a way like a would love to have from the beginning?

Thanks a lot.

maxmyh

>Solution :

here is one way to do it

# to_dict with orientation as records
out=df.to_dict('records')
out
[{'first_name': 'Peter ', 'last_name': 'Johnsen ', 'age': 42},
 {'first_name': 'Mark ', 'last_name': 'Conner ', 'age': 32},
 {'first_name': 'Susanna ', 'last_name': 'Rock ', 'age': 36}]
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