from copy import deepcopy
tree={'A':['B','C'],
'B':['D','E'],
'C':['F','G']}
treedict=deepcopy(tree)
i need help here .i have a tree which is a dict containing lists.i wonder how i can insert a node in the top of the tree and at the bottoom here is what i tried
def InsertNodeInTreeBottom(newnode,nodeparent,treedict):
for k in treedict.iteritems():
if (k==nodeparent):
node=nodeparent
children=treedict[node]
children.append[newnode
return treedict
但即使在我尝试添加后,树中也没有变化。如何在Python代码中迭代并插入列表中
例如我想InsertNodeInTreeBottom(“X”,“F”,treedict),树 必须看起来像
tree={'A':['B','C'],
'B':['D','E'],
'C':['F','G']
'F':['x']}
Python字典是无序的。如果你想要一个有序的字典,试试collections.OrderedDict。 – Urban48 2015-02-06 10:47:55
你的问题有点模棱两可,代码格式不正确。也看看这个问题是否可以帮助你:http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python – 2015-02-06 10:50:38