Python:树状字典数据结构的实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17107973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: tree like implementation of dict datastructure
提问by Aashish P
I have dict object something similar to like this,
我有类似这样的 dict 对象,
topo = {
'name' : 'm0',
'children' : [{
'name' : 'm1',
'children' : []
}, {
'name' : 'm2',
'children' : []
}, {
'name' : 'm3',
'children' : []
}]
}
Now, i want to insert one more dict object let's say,
现在,我想再插入一个 dict 对象,让我们说,
{
'name' : 'ABC',
'children' : []
}
as child of dict named "m2" inside m2's children array.
作为 m2 的 children 数组中名为“m2”的 dict 的孩子。
Could you please suggest how should i go about it?
你能建议我该怎么做吗?
Should i go for a separate data structure implementation ?
我应该去单独的数据结构实现吗?
采纳答案by morningstar
I would suggest you first convert it to a data structure like this:
我建议您首先将其转换为这样的数据结构:
topo = {
'm0' : {
'm1' : {},
'm2' : {},
'm3' : {},
},
}
That is, you have made every value for the 'name' key be a key in a dictionary, and every value for the 'children' key be the value for that key, and changed it to a dictionary instead of a list.
也就是说,您已将 'name' 键的每个值都设置为字典中的一个键,并且将 'children' 键的每个值都设置为该键的值,并将其更改为字典而不是列表。
Now you don't need to assume beforehand the index position where m2 is found. You do need to know that m2 is inside m0, but then you can simply say
现在您不需要事先假设找到 m2 的索引位置。您确实需要知道 m2 在 m0 内,但是您可以简单地说
topo['m0']['m2']['ABC'] = {}
You can convert between formats with this code:
您可以使用以下代码在格式之间进行转换:
def verbose_to_compact(verbose):
return { item['name']: verbose_to_compact(item['children']) for item in verbose }
def compact_to_verbose(compact):
return [{'name':key, 'children':compact_to_verbose(value)} for key, value in compact]
Call them like this
像这样称呼他们
compact_topo = verbose_to_compact([topo]) # function expects list; make one-item list
verbose_topo = compact_to_verbose(compact_topo)[0] # function returns list; extract the single item
I am assuming the format you have is the direct interpretation of some file format. You can read it in that way, convert it, work with it in the compact format, and then just convert it back when you need to write it out to a file again.
我假设您拥有的格式是对某些文件格式的直接解释。您可以通过这种方式阅读、转换、以紧凑格式使用它,然后在需要再次将其写入文件时将其转换回来。
回答by TerryA
Add it in the dictionary as you normally would, with the use of .append():
像往常一样将它添加到字典中,使用.append():
topo['children'][1]['children'].append({'name' : 'ABC', 'children' : []})
topois now:
topo就是现在:
{
"name": "m0",
"children": [
{
"name": "m1",
"children": []
},
{
"name": "m2",
"children": [
{
"name": "ABC",
"children": []
}
]
},
{
"name": "m3",
"children": []
}
]
}
回答by Ivan
topo['children'].append({'name' : 'ABC',
'children' : []
})
回答by mawimawi
topo['children'][1]['children'].append({'name': 'ABC', 'children': []})
This adds the new dictionary under the children of the second child of topo:
这将在 topo 的第二个孩子的孩子下添加新字典:
{'children': [{'children': [], 'name': 'm1'},
{'children': [{'children': [], 'name': 'ABC'}], 'name': 'm2'},
{'children': [], 'name': 'm2'}],
'name': 'm0'}
But I would not use dict and list builtin objects for such a task - I'd rather create my own objects.
但是我不会将 dict 和 list 内置对象用于这样的任务 - 我宁愿创建自己的对象。
回答by Ali SAID OMAR
Your issue is a common Tree structure, you can consider to use http://pythonhosted.org/ete2/tutorial/tutorial_trees.htmland populate each node with your dict value (don't reinvent the wheel).
您的问题是常见的树结构,您可以考虑使用http://pythonhosted.org/ete2/tutorial/tutorial_trees.html并用您的 dict 值填充每个节点(不要重新发明轮子)。

