2013-02-01 48 views
3

我有一個名爲「玩家」的名單,由詞典組成。它看起來像這樣:如何向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文件中,以便按鍵/值整齊排列?

非常感謝!

+0

你嘗試過什麼工作還沒有? –

+0

究竟是什麼問題?瀏覽數據結構或生成Excel文件? – C2H5OH

+0

Excel可以導入csv文件。查找'csv'模塊。 ESP。 'DictWriter'。 – zch

回答

2

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

然後打開生成的spreadsheet.csv Excel文件。

注意:我正在運行Linux,因此我無法使用Microsoft Excel對其進行測試。這可以在LibreOffice Calc中運行,並提供一個電子表格,其中的鍵是列名稱,值位於其適當的列下。

+0

嘿,非常感謝。我跑了這個雖然和csv。文件沒有打開。它保存在某個地方嗎? –

+0

@AlexKlinghoffer在'writeheader'中有一個錯字。我會嘗試複製固定版本並重新運行它...應該在您運行腳本的任何位置生成'spreadsheet.csv'。 – 2013-02-01 01:14:22

+0

嘿邁克,我非常感謝你的幫助。我試圖再次複製,但是當我運行它,它只是說: 退出狀態:0 註銷 [進程完成] 任何其他建議? –

8

有一種方法可以將字典列表寫入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() 

我試過代碼,成功地

0

使用解決方案大熊貓

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