首页 > 解决方案 > 了解嵌套字典的 .get() 方法

问题描述

我有以下嵌套字典,我试图将值的布尔值返回到['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()方法的原因,但我相信我遗漏了一些东西。想法?

标签: python

解决方案


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


推荐阅读