簡體   English   中英

將簡單字典導出到 python 中的 Excel 文件中

[英]Export a simple Dictionary into Excel file in python

我是 python 的新手。 我有一個簡單的字典,其鍵和值如下

dict1 = {"number of storage arrays": 45, "number of ports":2390,......}

我需要將它們放入 excel 表中,如下所示

number of storage arrays 45
number of ports          2390

我有一本很大的字典。

Sassikant,

這將打開一個名為output.csv的文件,並將字典的內容輸出到電子表格中。 第一列將具有鍵,第二列將具有該值。

import csv

with open('output.csv', 'wb') as output:
    writer = csv.writer(output)
    for key, value in dict1.iteritems():
        writer.writerow([key, value])

您可以使用excel打開csv並將其保存為您想要的任何格式。

你可以使用熊貓。

import pandas as pd

dict1 = {"number of storage arrays": 45, "number of ports":2390}

df = pd.DataFrame(data=dict1, index=[0])

df = (df.T)

print (df)

df.to_excel('dict1.xlsx')

作為@Daniel Timberlake答案的擴展,這就是我發現的對我有用的方法。 我只是想將dict object (行)列表保存到 CSV 文件中,以后可以根據需要將其轉換為.xlsx格式。

from __future__ import annotations  # optional on Python 3.9+

from csv import DictWriter

def write_to_csv(rows: list[dict]):
    with open('./output.csv', 'w') as output:
        writer = DictWriter(output, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM