如何实现Python字典链式访问不抛异常,不存在键返回None?
可行,给你个实现方案
你想要的链式访问字典、不存在的路径最终返回None的需求完全可以实现,核心思路是让每次访问不存在的键时,返回一个能继续接受下标访问的“占位对象”,而不是直接返回None。
直接看代码实现:
class ChainableDict(dict): def __getitem__(self, key): try: value = super().__getitem__(key) # 如果值是字典,转成ChainableDict保持链式能力 if isinstance(value, dict): return ChainableDict(value) return value except KeyError: return _NullChain() class _NullChain: def __getitem__(self, _): return self def __repr__(self): return 'None' def __str__(self): return 'None'
测试你的场景:
# 初始化基础字典 base = ChainableDict({ "foo23": { "subfoo": { "subsubfoo": [2,3] } } }) # 访问存在的路径 foo23 = base["foo23"]["subfoo"]["subsubfoo"] print(foo23) # 输出: [2,3] # 访问不存在的路径 foo23 = base["noexist"]["nothereeither"]["nope"] print(foo23) # 输出: None
原理说明
ChainableDict继承自原生dict,访问存在的键时,若对应值是字典会自动包装成ChainableDict,保证后续链式下标访问的能力;若为普通值则直接返回。- 访问不存在的键时,返回
_NullChain实例,这个实例的__getitem__方法不管接收到什么键都会返回自身,链式访问不会中断;它的__str__和__repr__方法返回'None',所以打印时会输出你需要的结果。
内容的提问来源于stack exchange,提问作者Jiminion
相关产品推荐
相关产品推荐

