-1

I am trying to pull out some specific values from this output:

{'GigabitEthernet': [{'name': '1', 'ip': {'address': {'primary': {'address': '192.168.200.200', 'mask': '255.255.255.0'}}, 'Cisco-IOS-XE-ospf:router-ospf': {'ospf': {'authentication': {'key-chain': 'sv-10599'}, 'message-digest-key': [{'id': 1, 'md5': {'auth-key': 'cisco'}}], 'network': {'point-to-point': [None]}}}}, 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}, {'name': '2', 'shutdown': [None], 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}, {'name': '3', 'shutdown': [None], 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}]}

Ideally I would like to get the following values:

GigabitEthernet 1 192.168.200.200

GigabitEthernet 2 Shutdown

# determine interface IP addresses

 for interface_type_gig in device_config['Cisco-IOS-XE-native:native']['interface']['GigabitEthernet']:
    interface_name = 'GigabitEthernet ' + interface_type_gig['name']
    print(interface_name)
    interface_address = interface_type_gig['ip']['address']['primary']['address']
    print(interface_address)

I am able to get the ['name'] but not the IP address. Interface_address returns a KeyError: 1

I am not able to get figure out.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

You have nested dictionary. I can only assume as to what the full dataset looks like. Assuming if the ip key is present, you have the ip addresss, and if not present it's Shutdown, you can just check for that and iterate that way:

data = {'GigabitEthernet': [{'name': '1', 'ip': {'address': {'primary': {'address': '192.168.200.200', 'mask': '255.255.255.0'}}, 'Cisco-IOS-XE-ospf:router-ospf': {'ospf': {'authentication': {'key-chain': 'sv-10599'}, 'message-digest-key': [{'id': 1, 'md5': {'auth-key': 'cisco'}}], 'network': {'point-to-point': [None]}}}}, 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}, {'name': '2', 'shutdown': [None], 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}, {'name': '3', 'shutdown': [None], 'mop': {'enabled': False, 'sysid': False}, 'Cisco-IOS-XE-ethernet:negotiation': {'auto': True}}]}

for interface_type_gig in data['GigabitEthernet']:
    interface_name = 'GigabitEthernet ' + interface_type_gig['name']

    if 'ip' in interface_type_gig.keys():
        interface_address = interface_type_gig['ip']['address']['primary']['address']
    else:
        interface_address = 'Shutdown'

    print(interface_name)
    print(interface_address)
chitown88
  • 27,527
  • 4
  • 30
  • 59