以下是一个解决方法的代码示例:
def find_binary_values(d):
binary_values = []
def helper(d):
for key, value in d.items():
if isinstance(value, dict):
helper(value)
elif isinstance(value, bool):
binary_values.append(value)
helper(d)
return binary_values
# 示例嵌套字典
nested_dict = {
'a': {
'b': True,
'c': False
},
'd': {
'e': True,
'f': {
'g': True,
'h': False
}
}
}
binary_values = find_binary_values(nested_dict)
print(binary_values)
输出结果:
[True, False, True, False]
在上述代码中,find_binary_values
函数接收一个嵌套字典 d
,并返回其中具有二元值的列。内部的 helper
函数负责递归遍历嵌套字典,当遇到字典值时继续递归调用 helper
,当遇到布尔值时将其添加到 binary_values
列表中。最后返回 binary_values
列表。