我想做这个:
foo23 = base["foo23"]["subfoo"]["subsubfoo"]
print(foo23)
[2,3]
foo23 = base["noexist"]["nothereeither"]["nope"]
print(foo23)
None
使用 defaultdict 和专用词典,我似乎无法完成此任务。 第一次调用的访问失败可能会返回“None”,但随后的字段会因不可订阅而导致异常。只是想知道这是否可能。
优雅的随机深度方法来做到这一点:
tree = lambda: defaultdict(tree)
base = tree()
base["noexist"]["nothereeither"]["nope"]
现在,这会返回一个空的默认字典,您必须处理它,例如:
print(base["noexist"]["nothereeither"]["nope"] or None)
不太漂亮,但更重要的是,正好 3 层嵌套的特殊变体:
deep3 = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: None)))
print(deep3["noexist"]["nothereeither"]["nope"])
# None
话虽这么说,最干净的方法是使用特殊功能访问你的字典:
def access(obj, *keys, default=None):
if not keys:
return obj
head, *tail = keys
if head not in obj:
return default
return access(obj[head], *tail, default=default)
print(access(base, "foo23", "subfoo", "subsubfoo"))
# None