📜  Python程序在字典中查找最大值元组的键

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

Python程序在字典中查找最大值元组的键

给定一个值作为元组的字典,任务是编写一个Python程序来找到最大值元组的键。

例子:

方法 #1:使用max() + values() + next()

在此,使用 max() 找到所有元组值的最大值,并使用 values() 提取值。 next(),用于使用迭代器访问方法进行迭代,并将每个元组值与最大值进行比较。

Python3
# Python3 code to demonstrate working of
# Maximum tuple value key
# Using max() + values() + next()
  
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
    "k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# getting maximum value
max_val = max(test_dict.values(), key=lambda sub: sub[1])
  
# getting key with maximum value using comparison
res = next(key for key, val in test_dict.items() if val == max_val)
  
# printing result
print("The maximum key : " + str(res))


Python3
# Python3 code to demonstrate working of
# Maximum tuple value key
# Using list comprehension + max() + values()
  
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
    "k", 10), 'for': ("p", 11), 'geeks': ('m',  2)}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# getting maximum value
max_val = max(test_dict.values(), key=lambda sub: sub[1])
  
# getting key with maximum value using comparison
res = [key for key, val in test_dict.items() if val == max_val][0]
  
# printing result
print("The maximum key : " + str(res))


输出:

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

在这里,我们使用列表理解来执行获取所有最大匹配值的任务。使用 max() 获得最大值。

蟒蛇3

# Python3 code to demonstrate working of
# Maximum tuple value key
# Using list comprehension + max() + values()
  
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
    "k", 10), 'for': ("p", 11), 'geeks': ('m',  2)}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# getting maximum value
max_val = max(test_dict.values(), key=lambda sub: sub[1])
  
# getting key with maximum value using comparison
res = [key for key, val in test_dict.items() if val == max_val][0]
  
# printing result
print("The maximum key : " + str(res))

输出: