Home > Back-end >  Exporting from dicts list to excel
Exporting from dicts list to excel

Time:11-12

Beginner here, I wrote a code where I'd like to export each and every dict inside a list to excel. For now it exports only the last one - name:evan, age:25. I have no idea why. Terminal shows all data but when I try to export it shows the last one. I'd like 'name' and 'age' to be column headers and the corresponding data below

import pandas as pd

people = [
{
    'name':'corey', 
    'age':12,
},
{
    'name':'matt', 
    'age':15,
},
{
    'name':'evan', 
    'age':25
}]


for person in range(len(people)):
    print(people[person]['name'], people[person]['age'])


excel_dict = {}
for s in range(len(people)):
    excel_dict['p_name'] = (people[s]['name'])
    excel_dict['p_age'] = (people[s]['age'])
    df = pd.DataFrame(data=excel_dict, index=[0])
    df = (df.T)
    print (df)
    df.to_excel('dict1.xlsx')
    

CodePudding user response:

Try this solution:

import pandas as pd

people = [
{
    'name':'corey', 
    'age':12,
},
{
    'name':'matt', 
    'age':15,
},
{
    'name':'evan', 
    'age':25
}]


for person in people:
    print(person['name'], person['age'])

df = pd.DataFrame(people)
print(df)
df.to_excel('dict1.xlsx')

Output:

corey 12
matt 15
evan 25

    name  age
0  corey   12
1   matt   15
2   evan   25
  • Related