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