gpt4 book ai didi

python - 存储Excel中的字典

转载 作者:太空宇宙 更新时间:2023-11-03 20:42:58 24 4
gpt4 key购买 nike

我正在尝试用 Excel 制作字典。我写了一段代码,但它没有按预期提供字典。在一张政策 map 下,所有数据都应比其他政策 map 到达之前出现。您将从预期输出中得到它。

这是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']"}] 

请建议更好的代码以获得所需的输出。

最佳答案

这应该有效:

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)

关于python - 存储Excel中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56755959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com