-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  

but there is no change in the tree even after i try to add.

for example i would like InsertNodeInTreeBottom('X','F',treedict) ,the tree must look like

tree={'A':['B','C'],
      'B':['D','E'],
      'C':['F','G']
      'F':['x']}
lut4
  • 1
  • 1
  • python dictionaries are unordered. If you want an ordered dictionary, try collections.OrderedDict. – Urban48 Feb 06 '15 at 10:47
  • your question is a bit ambiguous and the code is badly formatted. also see if this question helps you: http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python – Kamyar Ghasemlou Feb 06 '15 at 10:50

2 Answers2

0

I supposed your objective is to insert an element within a list identified by one of the dictionary key.

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)

will produce:

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

Notes:

  • in python 3 there is no more iteritems for dict type.
  • you can't use [] for append as it is a function
  • dictionaries are unordered, so you can't really call them a tree. If you want to create a proper tree, you'd better use nested tuple, or set a dictionary semantic like 'left' and 'right' keys or build a proper class for it.
M'vy
  • 5,696
  • 2
  • 30
  • 43
0

Try this

def InsertNodeInTreeBottom(newnode,nodeparent,treedict):
    for k in treedict:
        if (k==nodeparent):
            node=nodeparent
            children=treedict[node]
            children.append(newnode)
    return treedict 
  • use children.append(newnode) for append new item in list

  • iterat on dict its return key

NIKHIL RANE
  • 4,012
  • 2
  • 22
  • 45