首页 > 解决方案 > 从excel存储字典

问题描述

我正在尝试从excel制作字典。我已经编写了一个代码,但它没有按预期提供字典。在一个策略映射下,所有数据都应该比其他策略映射来。您将从预期的输出中得到。

这是excel: Sheet1.xlsx

这是我的预期输出:

res1= {'Nodeb_IN_New':{'policy_id':107,'default':'class-default','mplsa':['h10','h11','l12','l13','l14'],'mpls':['h1','h2','l1'],'qos':[7,5,4],'nokia':'dscp-fc-map','dscp':['ef','af41,'af11','af21','af31']},'Nokia_SRAN_S1-MME_X2_IN':{'policy_id':'102',default':",'mplsa':['h15','h16'],'mpls':['h1'],'qos':[7],'nokia':'dscp-fc-map','dscp':['ef','nc1']}}

我写了这样的代码:

from xlrd import open_workbook

book = open_workbook('test.xlsx')
sheet = book.sheet_by_index(1)

# read header values into the list    
keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)]

dict_list = []
for row_index in range(1, sheet.nrows):
    d = {keys[col_index]: sheet.cell(row_index, col_index).value 
         for col_index in range(sheet.ncols)}
    dict_list.append(d)

print (dict_list)

并获得不同的输出:

[{'policy_map': 'Nodeb_IN_New', 'policy_id': 107.0, 'default': 'class-default', 'class': 'mobility-platinum', 'mplsa': 'h10', 'mpls': 'h1', 'qos': 7.0, 'nokia': 'dscp-fc-map', 'dscp': "['ef']"}, {'policy_map': '', 'policy_id': '', 'default': '', 'class': 'mobility-gold-new', 'mplsa': 'h11', 'mpls': 'h2', 'qos': 5.0, 'nokia': 'dscp-fc-map', 'dscp': "['af41']"}, {'policy_map': '', 'policy_id': '', 'default': '', 'class': 'mobility-silver-new', 'mplsa': 'l12 l13 l14', 'mpls': 'l1', 'qos': 4.0, 'nokia': 'dscp-fc-map', 'dscp': "['af11', 'af21', 'af31']"}, {'policy_map': 'Nokia_SRAN_S1-MME_X2_IN', 'policy_id': 102.0, 'default': '', 'class': 'Nokia_SRAN_mobility_platinum', 'mplsa': 'h15 h16', 'mpls': 'h1', 'qos': 7.0, 'nokia': 'dscp-fc-map', 'dscp': "['ef', 'nc1']"}] 

请根据需要提出更好的代码以获得输出。

标签: pythonexcelpython-3.xlistdictionary

解决方案


这应该有效:

result = {}
for row_index in range(1, sheet.nrows):
    result[sheet.cell(row_index, 0).value] = {keys[col_index]: sheet.cell(row_index, col_index).value 
                                              for col_index in range(1,sheet.ncols)}

print (result)

推荐阅读