Python – 测试字典中的所有值是否相同
给定一个字典,测试它的所有值是否相同。
Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 8}
Output : True
Explanation : All element values are same, 8.
Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 9}
Output : False
Explanation : All element values not same.
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们迭代所有值并与字典中的值进行比较,如果任何一个不同,则返回 False。
Python3
# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 5, "Best" : 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Flag to check if all elements are same
res = True
# extracting value to compare
test_val = list(test_dict.values())[0]
for ele in test_dict:
if test_dict[ele] != test_val:
res = False
break
# printing result
print("Are all values similar in dictionary? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using set() + values() + len()
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 5, "Best" : 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using set() to remove duplicates and check for values count
res = len(list(set(list(test_dict.values())))) == 1
# printing result
print("Are all values similar in dictionary? : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True
方法 #2:使用 set() + values() + len()
这是可以执行此任务的另一种方式。在此,我们使用 values() 提取所有值,并使用 set() 删除重复项。如果提取集的长度为 1,则假定所有值都相似。
Python3
# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using set() + values() + len()
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 5, "Best" : 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using set() to remove duplicates and check for values count
res = len(list(set(list(test_dict.values())))) == 1
# printing result
print("Are all values similar in dictionary? : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True