Python程序检查字典的值是否与列表中的顺序相同
给定一个字典,测试值是否与列表值按顺序排列。
Input : test_dict = {“gfg” : 4, “is” : 10, “best” : 11}, sub_list = [4, 10, 11]
Output : True
Explanation : Values are 4, 10, 11, same as list order. Hence True is returned.
Input : test_dict = {“gfg” : 4, “is” : 10, “best” : 11}, sub_list = [4, 11, 10]
Output : False
Explanation : Values are 4, 10, 11, list order is 4, 11, 10, not same order. Hence False is returned.
方法#1:使用循环
在这种情况下,我们迭代字典值和列表,并测试所有值是否有序,如果任何元素无序,则标记关闭。
Python3
# Python3 code to demonstrate working of
# Test for Ordered values from List
# Using loop
# initializing dictionary
test_dict = {"gfg" : 4, "is" : 10, "best" : 11, "for" : 19, "geeks" : 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [4, 10, 11, 19, 1]
idx = 0
res = True
for key in test_dict:
# checking for inequality in order
if test_dict[key] != sub_list[idx]:
res = False
break
idx += 1
# printing result
print("Are values in order : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test for Ordered values from List
# Using values() + comparison operators
# initializing dictionary
test_dict = {"gfg" : 4, "is" : 10, "best" : 11, "for" : 19, "geeks" : 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [4, 10, 11, 19, 1]
# comparing values with list
res = list(test_dict.values()) == sub_list
# printing result
print("Are values in order : " + str(res))
输出:
The original dictionary is : {‘gfg’: 4, ‘is’: 10, ‘best’: 11, ‘for’: 19, ‘geeks’: 1}
Are values in order : True
方法#2:使用values( ) +比较运算符
在这里,我们使用 values() 提取所有值,然后使用运算符来检查与列表的相等性。
蟒蛇3
# Python3 code to demonstrate working of
# Test for Ordered values from List
# Using values() + comparison operators
# initializing dictionary
test_dict = {"gfg" : 4, "is" : 10, "best" : 11, "for" : 19, "geeks" : 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [4, 10, 11, 19, 1]
# comparing values with list
res = list(test_dict.values()) == sub_list
# printing result
print("Are values in order : " + str(res))
输出:
The original dictionary is : {‘gfg’: 4, ‘is’: 10, ‘best’: 11, ‘for’: 19, ‘geeks’: 1}
Are values in order : True