📜  Python程序从字典中查找最大值,其键存在于列表中

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

Python程序从字典中查找最大值,其键存在于列表中

给定一个包含字典键和字典的列表,从字典值中提取最大值,其键存在于列表中。

例子:

方法#1:使用循环

这是可以执行此任务的方法之一。在这里,我们检查列表中存在的所有键以及最大值,然后返回可用的最大值。

Python3
# Python3 code to demonstrate working of 
# Maximum value from List keys
# Using loop 
  
# initializing dictionary
test_dict = {"Gfg": 4, "is" : 5, "best" : 9,
             "for" : 11, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list 
test_list = ["Gfg", "best", "geeks"]
  
res = 0
for ele in test_list:
      
    # checking for key in dictionary
    if ele in test_dict:
        res = max(res, test_dict[ele])
      
# printing result 
print("The required maximum : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Maximum value from List keys
# Using max() + list comprehension
  
# initializing dictionary
test_dict = {"Gfg": 4, "is" : 5, "best" : 9, 
             "for" : 11, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list 
test_list = ["Gfg", "best", "geeks"]
  
# maximum is 11, but not present in list, 
# hence 9 is output.
res = max([test_dict[ele] for ele in test_list
           if ele in test_dict])
  
# printing result 
print("The required maximum : " + str(res))


输出:

方法 #2:使用 max() + 列表理解

这是可以执行此任务的另一种方式。在这里,我们使用 max() 提取最大值,并使用速记列表理解来迭代值。

蟒蛇3

# Python3 code to demonstrate working of 
# Maximum value from List keys
# Using max() + list comprehension
  
# initializing dictionary
test_dict = {"Gfg": 4, "is" : 5, "best" : 9, 
             "for" : 11, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list 
test_list = ["Gfg", "best", "geeks"]
  
# maximum is 11, but not present in list, 
# hence 9 is output.
res = max([test_dict[ele] for ele in test_list
           if ele in test_dict])
  
# printing result 
print("The required maximum : " + str(res)) 

输出: