如何在python中找到字典中的最大值键

时间:2018-04-17 06:14:32

标签: python dictionary

我无法理解以下代码如何在字典中找到具有最大值的键。我知道第一个参数,即my_dict.keys()返回一个键列表。但我没有得到第二个参数..帮助我

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))

2 个答案:

答案 0 :(得分:0)

那么,归结为:

# Your key is what you use to compare
key_value_finder = lambda x: my_dict[x]
test_val = 0
sought_key = None

# All that max is doing is iterating through the list like this
for k in my_dict.keys():

    # Taking the value returned by the `key` param (your lambda)
    tmp_val = key_value_finder(k)

    # And retaining it if the value is higher than the current cache.
    if tmp_val > test_val:
         test_val = tmp_val
         sought_key = k

答案 1 :(得分:0)

找到最大值键的另一个解决方案:

d = { 'age1': 10, 'age2': 11}

max_value = max(d.values())
for k, v in d.items():
    if v == max_value:
        print(k)

说明:

使用max()

查找最大值

然后使用for循环迭代并检查等于迭代值的值

for k, v in d.items():
if v == max_value: