-2

i have a nested dic, i need loopover it to check if ip=x and cmd=y then take action xyz, how can i do that?

d={'ip': {'cmd': 'cmd_out'}, 'ip1': {'cmd1': 'cmd_out1'}}

i am able to get below:

for ip, cmd in d.items():
    print ip,cmd

out:-

ip {'cmd': 'cmd_out'}

ip1 {'cmd1': 'cmd_out1'}

what i want is something like below but not working:

for ip, cmd in d.items():

    if ip =='ip' and cmd=='cmd':

        print 'first IP' , ip  ### take action

    elif ip=='ip1' and cmd='cmd1':

        print "second ip" , ip   #####take action

i am new to python so simpler is better :)

Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
Raj Pathak
  • 41
  • 1
  • 7
  • 1
    Check here: http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python – metmirr Jan 02 '17 at 10:20

1 Answers1

1

In your d dict, ip is a key and the value is another dict holding the value of cmd. In order to match both, you have to iterate it like:

d={'ip': {'cmd': 'cmd_out'}, 'ip1': {'cmd1': 'cmd_out1'}}
x, y = 'ip', 'cmd_out'  # Variable holding `ip` and `cmd`

for k, v in d.items():
    if k == x and v['cmd'] == y:
        print 'SUCCESS: We Found it'

Note: In case you don't know, key in dict are unique.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126