📜  Python|检查键是否在字典中具有 Non-None 值

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

Python|检查键是否在字典中具有 Non-None 值

有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要查找字典的特定键是否有效,即它不是 False 或具有非 None 值。这种问题可能发生在机器学习领域。让我们讨论一些可以解决这个问题的方法。

方法#1:使用if
这个任务可以简单地使用条件运算符"if"来解决。 if语句自动检查任何语句的真实性,从而检查键的值。

# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using if
  
# Initialize dictionary
test_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Using if
# Check if key has Non-None value in dictionary
res = False
if test_dict['gfg']:
    res = True
      
# printing result 
print("Does gfg have a Non-None value? : " + str(res))
输出 :

方法 #2:使用bool() + get()
上述功能可一起用于执行此特定任务。 get执行获取与 key 对应的值的任务,并且bool函数检查真实性。

# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using bool() + get()
  
# Initialize dictionary
test_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Using bool() + get()
# Check if key has Non-None value in dictionary
res = bool(test_dict.get('gfg'))
      
# printing result 
print("Does gfg have a Non-None value? : " + str(res))
输出 :