gpt4 book ai didi

python - 在嵌套字典中搜索关键树

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:03 24 4
gpt4 key购买 nike

我想检查嵌套字典中是否存在键元组,类似于dict.get。其功能可以通过如下方式实现。

nested_dict = {
'x': 1,
'a': {
'b': {
'c': 2,
'y': 3
},
'z': 4
}
}

def check(nested, *path):
for key in path:
if isinstance(nested, dict) and key in nested:
nested = nested[key]
else:
return False
return True


check(nested_dict, 'a', 'b', 'c') # True
check(nested_dict, 'x') # True
check(nested_dict, 'a', 'b', 'y') # True
check(nested_dict, 'a', 'z') # True

check(nested_dict, 'y') # False
check(nested_dict, 'a', 'y') # False
check(nested_dict, 'a', 'b', 'c', 'y') # False

是否有更清晰的(或者更好的是内置的)方法来执行此操作?

最佳答案

对于 python 3.x,请执行 from functools import reduce

您可以包装 try .. except KeyError (和 TypeError)并返回适当的 bool 值:

>>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict)
2
>>> reduce(lambda x,y: x[y], ["a", "b", "d"], nested_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
KeyError: 'd'
<小时/>

PS:这些行有时写起来很有趣。但老实说,我会在任何生产代码中使用您的版本。

关于python - 在嵌套字典中搜索关键树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38863540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com