📌  相关文章
📜  Python – 测试元素是否是字典的一部分

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

Python – 测试元素是否是字典的一部分

给定一个字典,测试 K 是否是字典的键或值的一部分。

方法 #1:使用 any() + items() + 生成器表达式

上述功能的组合可以用来解决这个问题。在此,我们使用 any() 检查任何元素,并且 items() 用于提取字典的所有键和值。

Python3
# Python3 code to demonstrate working of 
# Test if element is part of dictionary
# Using any() + generator expression + items()
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "Gfg"
  
# using any() to check for both keys and values 
res = any(K == key or K == val for key, val in test_dict.items())
  
# printing result 
print("Is K present in dictionary? : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Test if element is part of dictionary
# Using chain.from_iterables() + items()
from itertools import chain
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "Gfg"
  
# flattening key-values and then checking
# using in operator
res = K in chain.from_iterable(test_dict.items())
  
# printing result 
print("Is K present in dictionary? : " + str(res))


输出
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
Is K present in dictionary? : True

方法 #2:使用 chain.from_iterables() + items()

上述功能的组合可以用来解决这个问题。在此,我们将所有项目展平,然后检查是否存在 K 是任何项目()。

Python3

# Python3 code to demonstrate working of 
# Test if element is part of dictionary
# Using chain.from_iterables() + items()
from itertools import chain
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "Gfg"
  
# flattening key-values and then checking
# using in operator
res = K in chain.from_iterable(test_dict.items())
  
# printing result 
print("Is K present in dictionary? : " + str(res)) 
输出
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
Is K present in dictionary? : True