将嵌套字典转换为列表 [英] Converting a nested dictionary to a list
问题描述
我知道这里有很多字典要列出问题,但是我找不到适合我情况的信息,所以我要提出新的问题。
I know there are many dict to list questions on here but I can't quite find the information I need for my situation so I'm asking a new quetion.
某些背景:我正在为模型使用分层程序包,并且生成树结构的内置函数会输出一个嵌套循环以指示父代,子代等。我的目标是保持逻辑在视图中并输出一个列表,以便我可以在模板中对其进行遍历。
Some background: I'm using a hierarchical package for my models and the built-in function which generates the tree structure outputs a nested loop to indicate parents, children, etc. My goal is to keep the logic in views and output a list so that I can simply loop over it in my templates.
这是我的数据,在树结构中:
Here is my data, in the tree structure:
1
-1.1
--1.1.1
---1.1.1.1
--1.1.2
-1.2
--1.2.1
--1.2.2
-1.3
这是我得到的嵌套字典
{
<Part: 1.1>:
{
<Part: 1.1.1>:
{
<Part: 1.1.1.1>: {}
},
<Part: 1.1.2>: {}
},
<Part: 1.2>:
{
<Part: 1.2.1>: {},
<Part: 1.2.2>: {}
},
<Part: 1.3>: {}
}
或者如果您不喜欢我尝试分解的方式,这是我得到的内容:
or if you don't like the way I tried to break it up, here is what I get in a single line:
{<Part: 1.1>: {<Part: 1.1.1>: {<Part: 1.1.1.1>: {}}, <Part: 1.1.2>: {}}, <Part: 1.2>: {<Part: 1.2.1>: {}, <Part: 1.2.2>: {}}, <Part: 1.3>: {}}
我想要得到的是:
[<Part: 1.1>, <Part: 1.1.1>, <Part: 1.1.1.1>, <Part: 1.1.2>, <Part: 1.2>, <Part: 1.2.2>, <Part: 1.2.1>, <Part: 1.3>,]
我只是尝试遍历 dict.items
中的键,但后来我只获取顶级键(1.1,1.2,1.3)
我需要做些什么才能更深入?
I've tried just iterating over the key in dict.items
but then I only get the top level keys (1.1, 1.2, 1.3)
What do I need to do to get deeper?
谢谢!
推荐答案
我认为递归可以成为您的朋友:
I think recursion can be your friend :
top = {"<Part: 1.1>": {"<Part: 1.1.1>": {"<Part: 1.1.1.1>": {}}, "<Part: 1.1.2>": {}}, "<Part: 1.2>": {"<Part: 1.2.1>": {}, "<Part: 1.2.2>": {}}, "<Part: 1.3>": {}}
def grab_children(father):
local_list = []
for key, value in father.iteritems():
local_list.append(key)
local_list.extend(grab_children(value))
return local_list
print grab_children(top)
这篇关于将嵌套字典转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!