5

I have a nested python dictionary like this

{  
 "node":{  
  "node1":{  
     "node1.1":{  

     },
     "node1.2":{  

     }
  },
  "node2":{  
     "node2.1":{  
        "node2.1.1":{  

        }
     }
  }
 }
}

What I am trying to implement is a tree structure where I can add children to any parent elements. Is there a way to update values of nested dictionary using keys?

Ajai
  • 901
  • 9
  • 21
  • 1
    You can implement a simple `tree class` and try trace tree for find specific `key` you want – ᴀʀᴍᴀɴ Jan 12 '16 at 15:37
  • you should look at dict.get and dict.update, they may be helpful to you. Your question is however very very broad and I don't see that a proper answer can be made. – firelynx Jan 12 '16 at 15:45
  • 1
    Ajai - What you need is a recursive function which peels each layer of dictionary ( checks types using isinstance(value, dict) ) and keeps updating nested dictionary and update that to main dictionary. Please post very specific questions and I can give you exact code for you. – NullException Sep 14 '17 at 18:30

2 Answers2

5

if you don't know the path in the tree you can do something like this

my_tree={  
     "node":{
         "node1":{
             "node1.1":{},
             "node1.2":{}
             },
         "node2":{
             "node2.1":{
                 "node2.1.1":{}
                 }
             }
         }
     }

def update_tree(tree,key,value):
    """Return true if update, else false"""
    if key in tree:
        tree[key].update(value)
        return True
    for branch in tree.values():
        if update_tree(branch,key,value):
            return True
    return False

test

>>> import pprint
>>> pprint.pprint(my_tree)
{'node': {'node1': {'node1.1': {}, 'node1.2': {}},
          'node2': {'node2.1': {'node2.1.1': {}}}}}
>>> update_tree(my_tree,"node2.1",{"node2.1.2":{}})
True
>>> pprint.pprint(my_tree)
{'node': {'node1': {'node1.1': {}, 'node1.2': {}},
          'node2': {'node2.1': {'node2.1.1': {}, 'node2.1.2': {}}}}}
>>> 

EDIT

implementing a simple tree class, it would be something like this

class Tree(object):
    def __init__(self,value=None,*branchs):
        self.value  = value
        self.branchs = list(branchs)

    def update(self,parent,value):
        if self.value == parent:
            self.branchs.append(value)
            return True
        for branch in self.branchs:
            if branch.update(parent,value):
                return True
        return False

    def printTree(self,nivel=0):
        print( " "*nivel + str(self.value))
        for branch in self.branchs:
            branch.printTree(nivel+4)


my_tree_class=Tree("node",
                   Tree("node1",
                        Tree("node1.1"),
                        Tree("node1.2")
                        ),
                   Tree("node2",
                        Tree("node2.1",
                             Tree("node2.1.1")
                             )
                        )
                   )

test

>>> my_tree_class.printTree()
node
    node1
        node1.1
        node1.2
    node2
        node2.1
            node2.1.1
>>> my_tree_class.update("node2.1",Tree("node2.1.2"))
True
>>> my_tree_class.printTree()
node
    node1
        node1.1
        node1.2
    node2
        node2.1
            node2.1.1
            node2.1.2
>>>     

the details of the tree class depend on the kind of tree you want

Copperfield
  • 8,131
  • 3
  • 23
  • 29
-2

Is this what you're looking for?

dict['node']['node1']['node1.2'] = 'new value'
dict
{'node': {'node1': {'node1.2': 'new value', 'node1.1': {}}, 'node2': {'node2.1': {'node2.1.1': {}}}}}
Oliver S.
  • 39
  • 6