如何将字典列表输出到Excel工作表?

imzjd6km  于 2023-05-01  发布在  其他
关注(0)|答案(4)|浏览(265)

我有一个名为“玩家”的列表,它由字典组成。它看起来像这样:

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文件中,使其按键/值整齐地组织起来?

jk9hmnmh

jk9hmnmh1#

有一种方法可以将字典列表写入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 the dict object calls items randomly

wb=Workbook("New File.xlsx")
ws=wb.add_worksheet("New Sheet") # Or leave it blank. The 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()

我尝试了代码,它成功地工作了。

6rqinv9w

6rqinv9w2#

Pandas解决方案

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, 'dailyFreePlayed': 2, 'user': 'Player3', 'bank': 3.1},
{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player4', 'bank': 0.32}]

df = pd.DataFrame.from_dict(players)

print (df)

df.to_excel('players.xlsx')
ni65a41a

ni65a41a3#

xlsxwriter库非常适合创建.xlsx文件(最初由Fatih 1923提到)。
下面的代码片段从一个dicts列表中生成一个.xlsx文件,同时声明顺序显示的名称

import xlsxwriter

# ...

def create_xlsx_file(file_path: str, headers: dict, items: list):
    with xlsxwriter.Workbook(file_path) as workbook:
        worksheet = workbook.add_worksheet()
        worksheet.write_row(row=0, col=0, data=headers.values())
        header_keys = list(headers.keys())
        for index, item in enumerate(items):
            row = map(lambda field_id: item.get(field_id, ''), header_keys)
            worksheet.write_row(row=index + 1, col=0, data=row)

用途

headers = {
    'bank': 'Money in Bank',
    'dailyWinners': 'Daily Winners',
    'dailyFree': 'Daily Free',
    'user': 'User',
}

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

create_xlsx_file("my xslx file.xlsx", headers, players)

💡 注意-headers dict表示订单显示名称。如果你没有使用Python 3。6+,在headers中使用OrderedDict,因为dict中的顺序不保留

brccelvz

brccelvz4#

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进行测试。这在LibreOffice Calc中起作用,并给出一个电子表格,其中键是列名,值在相应的列下。

相关问题