python - 了解嵌套字典的 .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()
方法的原因,但我相信我遗漏了一些东西。想法?
解决方案
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
推荐阅读
- javascript - React onChange 功能不会触发,不允许我更改输入值
- python - 使用 Plotly Python 可视化 SVG
- python - AttributeError:“命名空间”对象没有属性“featurizer_model_path”
- powershell - 使用 AppVeyor CI 为 Windows(小于 5.1)和 Core(6 或更高)测试 Powershell 模块/脚本
- javascript - 如何修复点击时动态变化高度的工具提示?
- reactjs - 如何解决 React 组件的 YARN 编译错误?
- python - 用 pyppette 抓取网页,但网站阻止了我
- python - 查找方差最大的股票并将其与数据框的第一列交换
- typescript - const enum HttpStatusCode 如何工作?
- xpath - 使用 Xpath 1.0 提取最后一个单词