如何用Python向Excel编写字典 [英] How to write a Dictionary to Excel in Python

查看:138
本文介绍了如何用Python向Excel编写字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有以下字典,代表从-到距离矩阵。

I have the following dictionary in python that represents a From - To Distance Matrix.

graph = {'A':{'A':0,'B':6,'C':INF,'D':6,'E':7},

         'B':{'A':INF,'B':0,'C':5,'D':INF,'E':INF},

         'C':{'A':INF,'B':INF,'C':0,'D':9,'E':3},

         'D':{'A':INF,'B':INF,'C':9,'D':0,'E':7},

         'E':{'A':INF,'B':4,'C':INF,'D':INF,'E':0}

         }

是否可以输出这个矩阵到Excel或CSV文件,使其具有以下格式?我已经研究过使用csv.writer和csv.DictWriter,但无法产生所需的输出。

Is it possible to output this matrix into excel or to a csv file so that it has the following format? I have looked into using csv.writer and csv.DictWriter but can not produce the desired output.

推荐答案

您可以根据该字典创建熊猫数据框,然后保存为CSV或Excel:

You may create a pandas dataframe from that dict, then save to CSV or Excel:

import pandas as pd
df = pd.DataFrame(graph).T  # transpose to look just like the sheet above
df.to_csv('file.csv')
df.to_excel('file.xls')

这篇关于如何用Python向Excel编写字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆