Python - 字典中的最大记录值键
有时,在处理字典记录时,我们可能会遇到需要在列表中找到嵌套记录的特定键的最大值的键的问题。这可以在 Web 开发和机器学习等领域得到应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们遍历每个键的键并分配给 max,即嵌套记录中所需键的最大值。
# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using loop
# initializing dictionary
test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},
'is' : {'Manjeet' : 8, 'Himani' : 9},
'best' : {'Manjeet' : 10, 'Himani' : 15}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing search key
key = 'Himani'
# Maximum record value key in dictionary
# Using loop
res = None
res_max = 0
for sub in test_dict:
if test_dict[sub][key] > res_max:
res_max = test_dict[sub][key]
res = sub
# printing result
print("The required key is : " + str(res))
输出 :
The original dictionary is : {‘best’: {‘Himani’: 15, ‘Manjeet’: 10}, ‘gfg’: {‘Himani’: 10, ‘Manjeet’: 5}, ‘is’: {‘Himani’: 9, ‘Manjeet’: 8}}
The required key is : best
方法 #2:使用max()
+ lambda函数
这是解决此问题的一种线性方法。在此,我们使用 max key 参数执行迭代任务,传递一个绑定所需逻辑的 lambda函数。
# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using max() + lambda function
# initializing dictionary
test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},
'is' : {'Manjeet' : 8, 'Himani' : 9},
'best' : {'Manjeet' : 10, 'Himani' : 15}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing search key
key = 'Himani'
# Maximum record value key in dictionary
# Using max() + lambda function
res = max(test_dict, key = lambda sub: test_dict[sub][key])
# printing result
print("The required key is : " + str(res))
输出 :
The original dictionary is : {‘best’: {‘Himani’: 15, ‘Manjeet’: 10}, ‘gfg’: {‘Himani’: 10, ‘Manjeet’: 5}, ‘is’: {‘Himani’: 9, ‘Manjeet’: 8}}
The required key is : best