从带有dic的键中提取特定值

问题描述 投票:0回答:2

我正在尝试从键'ip'中提取特定值,在此示例中为192.168.200.200,但是在某些情况下,它会有所不同,并且可能不止一个。我是python新手,有人可以帮我提取这些值吗?

# import functions
from cisco_xe_api import *

# define variables
device_config = api_get_conf()

# Rule SV-105995r2_rule: The Cisco router must be configured to implement message
# authentication for all control plane protocols.
def sv105995r2rule_ospf():
    #device_config = api_get_conf()
    routing_protocol = device_config['Cisco-IOS-XE-native:native']['router']
    ospf_networks = device_config['Cisco-IOS-XE-native:native']['router']['Cisco-IOS-XE-ospf:router-ospf']['ospf']
    protocol_intf = device_config['Cisco-IOS-XE-native:native']['interface']
    if 'Cisco-IOS-XE-ospf:router-ospf' in routing_protocol.keys():
       print('\nOSPF is configured on this device. Checking for MD5 authentication.'
       print(ospf_networks.items())

这里是打印语句的输出:

OSPF is configured on this device. Checking for MD5 authentication.
dict_items([('process-id', [{'id': 100, 'area': [{'area-id': 0, 'authentication': {'message-digest': [None]}}], 'network': [{'ip': '192.168.200.200', 'wildcard': '0.0.0.0', 'area': 0}]}])])

感谢您的帮助!

python python-3.x dictionary
2个回答
0
投票

结构是字典→列表→字典→列表→字典,因此在您的示例中,您可以像这样获得IP:

ospf_networks['process-id'][0]['network'][0]['ip']

我对您所使用的API一无所知,但假设任何列表中可能包含多个项目,则打印所有IP看起来像这样:

for d0 in ospf_networks['process-id']:
    for d1 in d0['network']:
        print(d1['ip'])

1
投票

对于您提供的示例,获取ip的代码为:

ospf_networks['process_id'][0]['network'][0]['ip']

它是这样的:

  • 这就是我们得到的值键'process_id'。
  • 此值为列表。
  • 在此示例中,此列表中只有一个元素。
  • 我们得到该元素,它是一个字典。
  • 此字典具有以下键:'id','area','network'。
  • 我们通过键'network'获得价值。
  • 这些值是另一个具有单个元素的列表。
  • 这是另一个带有键“ ip”,“通配符”和“区域”的字典。
  • 我们通过'ip'键获取值。

现在要获得多个IP地址ospf_networks指示,它将完全取决于它们在结构中的位置。

© www.soinside.com 2019 - 2024. All rights reserved.