在python中将一个简单的字典导出到Excel文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28555112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export a simple Dictionary into Excel file in python
提问by sasikant
I am new to python. I have a simple dictionary for which the key and values are as follows
我是python的新手。我有一个简单的字典,其键和值如下
dict1 = {"number of storage arrays": 45, "number of ports":2390,......}
i need to get them in a excel sheet as follows
我需要将它们放入 Excel 表中,如下所示
number of storage arrays 45
number of ports 2390
I have a very big dictionary.
我有一本很大的字典。
回答by Daniel Timberlake
Sassikant,
萨西坎特,
This will open a file named output.csv
and output the contents of your dictionary into a spreadsheet. The first column will have the key, the second the value.
这将打开一个名为的文件并将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])
You can open the csv with excel and save it to any format you'd like.
您可以使用 excel 打开 csv 并将其保存为您喜欢的任何格式。
回答by Chankey Pathak
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')