📌  相关文章
📜  Python程序检查字典的值是否与列表中的顺序相同

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

Python程序检查字典的值是否与列表中的顺序相同

给定一个字典,测试值是否与列表值按顺序排列。

方法#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))


输出:

方法#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)) 

输出: