了解嵌套字典的.get()方法

时间:2019-08-19 21:26:41

标签: python

我有以下嵌套的字典,并且我试图将值的布尔值返回给函数内部的['is_up']键:

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}}}}}}

我能够完成这项工作的唯一方法是使用嵌套的for循环:

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

当我用此行替换嵌套循环时:

return ios_output.get('global').get('peers').get('10.10.10.1').get('is_up') == True

我得到:

AttributeError: 'NoneType' object has no attribute 'get' dictionary

我认为有一种比利用嵌套循环更好的方法-这就是为什么我尝试使用.get()方法,但是我认为我缺少了一些东西。有想法吗?

1 个答案:

答案 0 :(得分:3)

'10 .10.10.1'在您的字典中不存在,因此为AttributeError。也就是说,get方法接受第二个默认参数,默认情况下为None。也就是说,如果要到达特定节点,则需要传递第二个参数,这将是一个空的字典:

return ios_output.get('global', {}).get('peers', {}).get('10.10.10.1', {}).get('is_up')

鉴于“ 10.10.10.1”不存在,将返回None