📌  相关文章
📜  Python - 检查字典中的所有值是否都是 K

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

Python - 检查字典中的所有值是否都是 K

在使用字典时,我们可能会遇到一个问题,我们需要确保字典中的所有值都是 K。在检查启动状态或检查可能发生的错误/操作时,可能会发生此类问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用all() + 字典理解
上述功能的组合可用于执行以下任务。 all函数检查每个键,字典理解检查 K 值。

# Python3 code to demonstrate working of
# Test if all values are K in dictionary
# Using all() + dictionary comprehension
  
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
  
# Printing original dictionary 
print("The original dictionary is : " + str(test_dict))
  
# Initialize K 
K = 8
  
# using all() + dictionary comprehension
# Test if all values are K in dictionary
res = all(x == K for x in test_dict.values())
  
# printing result 
print("Does all keys have K value ? : " + str(res))
输出 :
The original dictionary is : {'gfg': 8, 'best': 8, 'is': 8}
Does all keys have K value ? : True

方法#2:使用循环
这个问题可以通过使用循环的蛮力策略来解决,我们将每个键等同于 K,如果所有元素都匹配 K,则返回 True。

# Python3 code to demonstrate working of
# Test if all values are K in dictionary
# Using loop
  
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
  
# Printing original dictionary 
print("The original dictionary is : " + str(test_dict))
  
# Initialize K 
K = 8
  
# using loop
# Test if all values are K in dictionary
res = True 
for key in test_dict:
    if test_dict[key] != K:
        res = False
  
# printing result 
print("Does all keys have K value ? : " + str(res))
输出 :
The original dictionary is : {'gfg': 8, 'best': 8, 'is': 8}
Does all keys have K value ? : True