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

Time:11-11

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:

[
{'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

CodePudding user response:

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}]
  • Related