2017-01-02 60 views
-2

我有一个嵌套的dic,我需要循环它来检查ip = x和cmd = y然后采取行动xyz,我该怎么做?需要关于python嵌套字典的帮助

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

我能够得到如下:

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

出来: -

ip {'cmd': 'cmd_out'} 

ip1 {'cmd1': 'cmd_out1'} 

我想要的是像下面,但不工作:

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 

我对Python来说是新的,所以更简单更好:)

+1

请点击这里:http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python – metmirr

回答

1

在你d字典,IP是一个键和值是另一个dict持有的cmd值。在为了匹配,你必须遍历它像:

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' 

注:如果你不知道,在dict关键是唯一的。