简体   繁体   中英

Exporting from dicts list to excel

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')
    

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'])


excel_dict = {}
file_number = 1

for person in people:
    excel_dict['p_name'] = (person['name'])
    excel_dict['p_age'] = (person['age'])
    df = pd.DataFrame(data=excel_dict, index=[0])
    df = (df.T)
    print (df)
    file_name = 'dict'+str(file_number)+'.xlsx'
    df.to_excel(file_name)
    file_number+=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM