Python程序从字典中查找最大值,其键存在于列表中
给定一个包含字典键和字典的列表,从字典值中提取最大值,其键存在于列表中。
例子:
Input : test_dict = {“Gfg”: 4, “is” : 5, “best” : 10, “for” : 11, “geeks” : 3}, test_list = [“Gfg”, “best”, “geeks”]
Output : 10
Explanation : Max value is 11, but not present in list, 10 is of key best, which is also in list.
Input : test_dict = {“Gfg”: 4, “is” : 5, “best” : 10, “for” : 11, “geeks” : 3}, test_list = [“Gfg”, “best”, “geeks”, “for”]
Output : 11
Explanation : Max. value, 11, present in list as well.
方法#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))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: 5, ‘best’: 9, ‘for’: 11, ‘geeks’: 3}
The required maximum : 9
方法 #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))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: 5, ‘best’: 9, ‘for’: 11, ‘geeks’: 3}
The required maximum : 9