Alex
Alex

Reputation: 65

Update values in a dict with a recursive procedure python

sorry if it was already asked but I could not find any answer in the knowledge base. I'm trying to update values in a dictionary via a recursive procedure, here below you have the code:

 import os

 incmds={
     'ip':{
         'link':{
             'show':[]
         },
         'addr':{
             'show':[]
         },
         'route':{
             'show':[]
         }
     }
 }

 cmd_list=[]

 def go_through_dict(parental_key,passeddict,cmd_list):
     for k,v in passeddict.items():
         t=parental_key+' '+k
         if isinstance(v, dict):
             go_through_dict(t,v,cmd_list)
         else:
             t=t.strip()
             cmd_list.append(t)
             with os.popen(t) as f:
 #                print 'Issueing the command: '+t
                 v=f.readlines()
 #                print 'Result:',v
 ## main ##
 cmd=''
 go_through_dict('',incmds,cmd_list)

 for cmd in cmd_list:
     print cmd

 print incmds

when I run it I see the inner value of the dict incmds are not updated. In fact eventually I get:

ip route show
ip link show
ip addr show
{'ip': {'route': {'show': []}, 'link': {'show': []}, 'addr': {'show': []}}}

I think that by default variables are passed by reference and hence if I modify something within the procedure once it terminates changes should be reflected outside. The thing is that I'm NOT modifying the values in the traditional way like this

incmds['ip']['addr']['show']=<output of the command>

This is just a POC and the goal is indeed to have some OS commands described as dict tree and have the output stored in the leaves.

How should I modify my procedures to really modify the leaves of my tree (meaning the values of the innest elements of the dict)?

Shall I keep track of the point in the tree and then "eval" the expression? Or How do it?

At the beginning I liked the idea of the recursive procedure because regardless of the size of my tree it was compact but now I'm facing the problem that I cannot update the values :-)

Thanks in advance,

Alex

Upvotes: 0

Views: 1620

Answers (1)

Błotosmętek
Błotosmętek

Reputation: 12927

It boils down to the fact that when you iterate over a dictionary:

for k,v in passeddict.items():

and modify v, you're not modifying a dictionary item, you're just assigning a new value to v . You should replace:

v=f.readlines()

with:

passeddict[k] = f.readlines()

Upvotes: 2

Related Questions