Reputation: 109
I have the following nested dictionary and I'm trying to return the boolean of the value to the ['is_up']
key inside of a function:
ios_output = {'global': {'router_id': '10.10.10.1',
'peers': {'10.10.10.2': {'local_as': 100,
'remote_as': 100,
'remote_id': '0.0.0.0',
'is_up': False,
'is_enabled': True,
'description': '',
'uptime': -1,
'address_family': {'ipv4': {'received_prefixes': -1,
'accepted_prefixes': -1,
'sent_prefixes': -1}}},
'10.10.10.3': {'local_as': 100,
'remote_as': 100,
'remote_id': '0.0.0.0',
'is_up': False,
'is_enabled': True,
'description': '',
'uptime': -1,
'address_family': {'ipv4': {'received_prefixes': -1,
'accepted_prefixes': -1,
'sent_prefixes': -1}}},
'10.10.10.5': {'local_as': 100,
'remote_as': 100,
'remote_id': '172.16.28.149',
'is_up': True,
'is_enabled': True,
'description': '',
'uptime': 3098,
'address_family': {'ipv4': {'received_prefixes': 0,
'accepted_prefixes': 0,
'sent_prefixes': 0}}}}}}
The only way I've been able to get this work is by using a nested for loop:
for k, v in ios_output.items():
for y in v.values():
if type(y) == dict:
for z in y.values():
return z['is_up'] == True
When I replace the nested loop with this line:
return ios_output.get('global').get('peers').get('10.10.10.1').get('is_up') == True
I get:
AttributeError: 'NoneType' object has no attribute 'get' dictionary
I'm of the opinion that there's got to be a better way to than leveraging a nested loop - which is why I'm attempting to use the .get()
method but I believe I'm missing something. Thoughts?
Upvotes: 1
Views: 77
Reputation: 5950
10.10.10.1
is not present in your dict, hence the AttributeError
.
That said, the get
method accepts a second, default parameter, which is None
by default.
That said, if you want to reach the specific node, you need to pass a second parameter, which would be an empty dict:
return ios_output.get('global', {}).get('peers', {}).get('10.10.10.1', {}).get('is_up')
Which, given that 10.10.10.1
doesn't exist would return None
Upvotes: 3