将树结构从列表转换为Python字典
我想转换一个树结构,表示为这样的列表将树结构从列表转换为Python字典,python,Python,我想转换一个树结构,表示为这样的列表 ['access_ctrl_allow', ['description', ['Access Control - Allow']], ['type', ['4']], ['metadata'], ['output', ['0']], ['rule', ['0', ['enabled', ['1']], ['action', ['type', ['accept_conn']]], ['match', ['services
['access_ctrl_allow',
['description', ['Access Control - Allow']],
['type', ['4']],
['metadata'],
['output', ['0']],
['rule',
['0',
['enabled', ['1']],
['action', ['type', ['accept_conn']]],
['match',
['services',
['0',
['name', ['DHCP']],
['trigger',
['0',
['protocol', ['17']],
['dst', ['start', ['67']], ['end', ['67']]],
['src', ['start', ['67']], ['end', ['68']]]]]]]]]]]
进入Python字典,如下所示:
{'access_ctrl_allow': {'output': '0',
'type': '4',
'description': 'Access Control - Allow',
'rule': {'0': {'action': {'type': 'accept_conn'},
'enabled': '1',
'match': {'services': {'0': {'trigger': {'0': {'src': {'start': '67',
'end': '68'},
'dst': {'start': '67', 'end': '67'},
'protocol': '17'}},
'name': 'DHCP'}}}}},
'metadata': {}}}
我有这样做的代码,似乎产生正确的输出
def dictify(data):
k, v = data[0], data[1:]
if len(v) == 0:
return {k: {}}
elif len(v) == 1 and len(v[0]) == 1:
return {k: v[0][0]}
else:
new = {}
for datum in v:
new.update(dictify(datum))
return {k: new}
…但感觉很笨重。你能为清理这个提供一些建议吗?特别是,需要取消对列表中列表的引用(
v[0][0]
)对我来说意味着必须有更好的方法。如果您愿意接受稍微不同的输出,您可以使用设置默认值
:
import json
d={}
def rec(lst,d):
for i in lst:
if not isinstance(i,list):
child=d.setdefault(i,{})
else:
rec(i,child)
rec(lst,d)
print json.dumps(d,indent=3)
out:
{
"access_ctrl_allow": {
"output": {
"0": {}
},
"type": {
"4": {}
},
"description": {
"Access Control - Allow": {}
},
"rule": {
"0": {
"action": {
"type": {
"accept_conn": {}
}
},
"enabled": {
"1": {}
},
"match": {
"services": {
"0": {
"trigger": {
"0": {
"src": {
"start": {
"67": {}
},
"end": {
"68": {}
}
},
"dst": {
"start": {
"67": {}
},
"end": {
"67": {}
}
},
"protocol": {
"17": {}
}
}
},
"name": {
"DHCP": {}
}
}
}
}
}
},
"metadata": {}
}
}
改用。这不是一个编程问题,也不是代码审查问题。这怎么不是一个编程问题呢?如果我还没有自己解决它,这只是一个编程问题吗?我可以删除我的代码,如果它能让你高兴的话。这里没有问题要解决。您自己也说过-这对输入数据有效,而且似乎是一种完全合理的递归方法。它符合您的数据和期望。你是要一班轮吗?怎么了?是否已被确定为瓶颈?不管怎样,它都不适合这样做。我的代码的早期版本正好生成了这个输出,但我不满意整个值都表示为键结果。另一方面,你的代码比我的短得多。谢谢