如何输出词典列表到excel工作表?
我有一个名为“玩家”的名单,由词典组成。 它看起来像这样:
players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06}, {'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0}, {'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}]
时间更长,但这是一个节选。 如何将这个词典列表输出到excel文件中,以便按键/值整齐排列?
非常感谢!
test.py
from csv import DictWriter players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06}, {'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0}, {'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}] with open('spreadsheet.csv','w') as outfile: writer = DictWriter(outfile, ('dailyWinners','dailyFreePlayed','dailyFree','user','bank')) writer.writeheader() writer.writerows(players)
运行python test.py
然后在Excel中打开生成的spreadsheet.csv
文件。
注:我正在运行Linux,所以我无法使用Microsoft Excel来testing。 这在LibreOffice Calc中起作用,并给出了一个电子表格,其中键是列名,值在其适当的列下。
有一种方法可以写出excel工作表的字典列表。 首先确保你有XlsxWriter package
。
from xlsxwriter import Workbook players = [{'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player1', 'bank': 0.06}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player2', 'bank': 4.0}, {'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}] ordered_list=["user","dailyWinners","dailyFree","bank"] #list object calls by index but dict object calls items randomly wb=Workbook("New File.xlsx") ws=wb.add_worksheet("New Sheet") #or leave it blank, default name is "Sheet 1" first_row=0 for header in ordered_list: col=ordered_list.index(header) # we are keeping order. ws.write(first_row,col,header) # we have written first row which is the header of worksheet also. row=1 for player in players: for _key,_value in player.items(): col=ordered_list.index(_key) ws.write(row,col,_value) row+=1 #enter the next row wb.close()
我尝试了代码,工作成功
使用pandas解决scheme
import pandas as pd players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06}, {'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0}, {'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}] df = pd.DataFrame.from_dict(players) print (df) df.to_excel('players.xlsx')
结合使用Python-Excel和JSON,可以轻松实现。