0

I am having trouble understanding how the following code finds the key with maximum value in a dictionary. I know first parameter i.e my_dict.keys() returns a list of keys. But I am not getting about 2nd parameter.. Help me out

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
Bulat
  • 720
  • 7
  • 15
heisenberg
  • 23
  • 3

2 Answers2

0

So, what that boils down to:

# 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
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • so the actual purpose of 1st parameter my_dict.keys() is to provide key as a paramater to the lambda function for returning the corresponding value and checking for max value repeatedly,is it? – heisenberg Apr 17 '18 at 06:33
0

One more solution to find the key of max value:

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

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

Explanation:

Find the maximum value using max()

Then using for loop iterate and check for value which is equal to iterating value

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