2015-02-06 81 views
-1
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']} 
+0

Python字典是無序的。如果你想要一個有序的字典,試試collections.OrderedDict。 – Urban48 2015-02-06 10:47:55

+0

你的問題有點模棱兩可,代碼格式不正確。也看看這個問題是否可以幫助你:http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python – 2015-02-06 10:50:38

回答

0

我認爲你的目標是通過一個標識的列表中插入一個元素的字典鍵。

from copy import deepcopy 

tree={'A':['B','C'], 
     'B':['D','E'], 
     'C':['F','G']} 

treedict=deepcopy(tree) 

def InsertNodeInTreeBottom(newnode,nodeparent,treedict): 
    for k, v in treedict.items(): 
     if (k==nodeparent): 
      treedict[k].append(newnode) 
    return treedict 

InsertNodeInTreeBottom('AA', 'B', treedict) 

會產生:

{'C': ['F', 'G'], 'B': ['D', 'E', 'AA'], 'A': ['B', 'C']} 

注:

  • 在Python 3沒有更多iteritemsdict類型。
  • 你不能使用[]append,因爲它是一個函數
  • 字典是無序的,所以你不能真的稱它們爲樹。如果你想創建一個合適的樹,你最好使用嵌套的tuple,或者設置一個字典語義,如'左'和'右'鍵或爲其構建適當的類。
+0

orderedDict有命令 – 2015-02-06 11:09:17

0

試試這個

def InsertNodeInTreeBottom(newnode,nodeparent,treedict): 
    for k in treedict: 
     if (k==nodeparent): 
      node=nodeparent 
      children=treedict[node] 
      children.append(newnode) 
    return treedict 
  • 使用children.append(newnode)對字典表中追加新項目

  • 所迭代其返回鍵