📜  Python – 测试字典的布尔值

📅  最后修改于: 2022-05-13 01:55:33.061000             🧑  作者: Mango

Python – 测试字典的布尔值

有时,在处理数据时,我们需要根据字典的真实值来接受或拒绝字典,即所有键都是布尔值是否为真。这类问题在数据预处理领域有可能的应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是解决此问题的蛮力方法。在这种情况下,如果我们发现第一次出现假值并从循环中中断,我们对每个键进行迭代并将其标记为假。

# Python3 code to demonstrate working of 
# Test Boolean Value of Dictionary
# Using loop
  
# initializing dictionary
test_dict = {'gfg' : True, 'is' : False, 'best' : True}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Test Boolean Value of Dictionary
# Using loop
res = True 
for ele in test_dict:
    if not test_dict[ele]:
        res = False 
        break
  
# printing result 
print("Is Dictionary True ? : " + str(res)) 
输出 :

方法 #2:使用all() + values()
这是解决此问题的一种速记方法。在此,all() 用于检查使用 values() 提取的所有值的状态。

# Python3 code to demonstrate working of 
# Test Boolean Value of Dictionary
# Using all() + values()
  
# initializing dictionary
test_dict = {'gfg' : True, 'is' : False, 'best' : True}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Test Boolean Value of Dictionary
# Using all() + values()
res = all(test_dict.values())
  
# printing result 
print("Is Dictionary True ? : " + str(res)) 
输出 :