Python – 测试自定义键是否等于字典中的 K
给定字典和自定义键列表,检查所有这些自定义键是否等于 K。
Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 10, “Geeks” : 10}, cust_keys = [“is”, “for”, “Geeks”], K = 10
Output : False
Explanation : “is” is having 8 as value not 10, hence False
Input : test_dict = {“Gfg” : 5, “is” : 10, “Best” : 10, “for” : 10, “Geeks” : 10}, cust_keys = [“is”, “for”, “Geeks”], K = 10
Output : True
Explanation : All keys have 10 as values.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此我们迭代每个自定义键并通过使用布尔变量跟踪来检查是否全部等于 K。
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# using loop to check for all keys
res = True
for key in cust_keys:
if test_dict[key] != K:
# break even if 1 value is not equal to K
res = False
break
# printing result
print("Are all custom keys equal to K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using all() + generator expression
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# returns true if all elements match K
res = all(test_dict[key] == K for key in cust_keys)
# printing result
print("Are all custom keys equal to K : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
方法 #2:使用 all() + 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用 all() 检查所有值,并且生成器表达式执行所需的迭代。
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using all() + generator expression
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# returns true if all elements match K
res = all(test_dict[key] == K for key in cust_keys)
# printing result
print("Are all custom keys equal to K : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True