2015-02-06 84 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)对字典表中追加新项目

  • 所迭代其返回键