Export a simple Dictionary into Excel file in python
Asked Answered
R

4

21

I am new to python. I have a simple dictionary for which the key and values are as follows

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

i need to get them in a excel sheet as follows

number of storage arrays 45
number of ports          2390

I have a very big dictionary.

Reparation answered 17/2, 2015 at 5:15 Comment(1)
Just export it to CSV using the csv module, and then import it into Excel. File - Save As in Excel to save it as .xlsxHorney
R
30

You can use pandas.

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')
Rudolfrudolfo answered 23/8, 2017 at 6:31 Comment(1)
what if I want to append similar data in same excel fileBrockwell
R
14

This will write the contents of the dictionary to output.csv. The first column will contain the keys, the second will contain the values.

import csv

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

You can open the csv with excel and save it to any format you'd like.

Rociorock answered 17/2, 2015 at 5:40 Comment(3)
brilliant idea, should use dict1.items() on py3Toadfish
Use "w+" instead of "wb" to be able to create a new file and not just write bytesShire
Use only "w" in with open('output.csv', 'w') as output:Reviviscence
O
0

As an extension to @Daniel Timberlake's answer, here's what I found worked for me. I simply wanted to save a list of dict object (rows) to a CSV file, which could then later be converted to .xlsx format if needed.

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)
Ovarian answered 2/9, 2022 at 21:39 Comment(0)
B
0

If it needs to be fast, just write the xlsx directly - which is a number of xml files in a zip container. The example code is too big to show here, but the interested user may have a look at pip download tabxlsx - the tabxlsx script converts any csv file into xlsx and back.

Bet answered 31/7, 2024 at 7:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.