【发布时间】:2021-04-10 06:55:48
【问题描述】:
所以我有一个与此类似的任意深度的嵌套字典:
sample_dict = {
'root_node': {
'child_1': {
'child_1a': {
'child_1a_a': {},
'child_1a_b': {},
...,
'child_1a_x': {}
},
'child_1b': {
'child_1b_a': {
'child_1b_a_a': {},
'child_1b_a_b': {},
...
},
'child_1b_b': {
'child_1b_b_a': {},
...
},
'child_1b_c': {}
}
},
'child_2': {
...
}
}
}
我需要把上面的字典转换成这样的:
sample_dict_output = {
'title':'root_node',
'key':'root_node',
'children':[
{ 'title':'child_1',
'key':'child_1',
'children':[
{'title':'child_1a',
'key':'child_1a',
'children':[
{'title': 'child_1a_a',
'key': 'child_1a_a'},
{'title': 'child_1a_b',
'key': 'child_1a_b'},
...
{'title': 'child_1a_x',
'key': 'child_1a_x'},
],},
{'title':'child_1b',
'key':'child_1b',
'children':[
{'title': 'child_1b_a',
'key': 'child_1b_a',
'children':[
{'title': 'child_1b_a_a',
'key': 'child_1b_a_a'},
{'title': 'child_1b_a_b',
'key': 'child_1b_a_b'},
...
],},
{'title': 'child_1b_b',
'key': 'child_1b_b',
'children':[
{'title': 'child_1b_b_a',
'key': 'child_1b_b_a'},
...,
],},
{'title': 'child_1b_c',
'key': 'child_1b_c'}
],
},
{ 'title':'child_2',
'key':'child_2',
'children':[...]
}
],
}
我尝试在 Stackoverflow 中搜索解决方案并尝试递归,但无济于事。因此,任何帮助将不胜感激(最好在 Python 3.x 中)。谢谢!
【问题讨论】:
-
你应该导航到字典,但这不一定是递归的。
-
你能不能开始用英文描述一下输出和输入之间的关系是什么? “...转换成这样的东西。”真的吗?
-
如果最外面的字典不是单例怎么办?整个输出不应该是一个列表吗?
标签: python python-3.x dictionary recursion nested