以下是一个遍历嵌套字典并将键的值为True的情况加入打印语句中的示例代码:
def print_true_values(dictionary):
for key, value in dictionary.items():
if isinstance(value, dict):
print_true_values(value)
elif value is True:
print(f"The value of key {key} is True")
# 示例嵌套字典
nested_dict = {
"key1": True,
"key2": False,
"key3": {
"key4": True,
"key5": {
"key6": False,
"key7": True
}
}
}
# 调用函数遍历字典并打印值为True的键
print_true_values(nested_dict)
输出结果:
The value of key key1 is True
The value of key key4 is True
The value of key key7 is True
在上面的示例中,我们定义了一个名为print_true_values
的函数,它接受一个嵌套字典作为参数。该函数使用递归来遍历字典的所有键值对。如果值是一个字典,则递归调用print_true_values
函数。如果值是True,则打印出键的值为True的消息。
然后,我们创建了一个示例嵌套字典nested_dict
,并调用print_true_values
函数来遍历字典并打印值为True的键。输出结果显示了键key1
、key4
和key7
的值为True的消息。
上一篇:遍历嵌套字典中特定键的迭代。