📜  Python|检查给定字典中的无值

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

Python|检查给定字典中的无值

很多时候,在使用字典时,我们希望检查一个非空字典,即检查给定字典中的 None 值。这在机器学习中找到了应用,我们必须提供没有任何值的数据。让我们讨论可以执行此任务的某些方式。

方法#1:使用all() + not operator + values()

上述功能的组合可用于执行此特定任务。在此,我们使用使用values函数提取的all函数检查所有值。 not运算符用于反转结果以检查任何 None 值。

# Python3 code to demonstrate working of
# Check for Non None Dictionary values
# Using all() + not operator + values()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using all() + not operator + values()
# Check for Non None Dictionary values
res = not all(test_dict.values())
  
# printing result 
print("Does Dictionary contain None value ? " + str(res))
输出 :
The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}
Does Dictionary contain None value ? True

方法 #2:使用in operator + values()

也可以使用 in运算符和值函数来执行此任务。我们只是在使用values函数提取的所有值中检查 None 并使用in运算符检查是否存在。

# Python3 code to demonstrate working of
# Check for Non None Dictionary values
# Using in operator + values()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using in operator + values()
# Check for Non None Dictionary values
res = None in test_dict.values()
  
# printing result 
print("Does Dictionary contain None value ? " + str(res))
输出 :
The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}
Does Dictionary contain None value ? True