square = {2: 4, -3: 9, -1: 1, -2: 4}
key1 = max(square)
print(key1) # 2
key2 = max(square, key = lambda k: square[k])
print(key2) # -3
key3 = square[key2]
print(key3) # 9
Q1: sorry if this question seems irrelevant but, how does square[k] works, I can't get the logic behind it every time I remove K, the answer would be the same as key1 Q2: How does the logic works with key3 resulting to 9
THANK YOU IN ADVANCE!!!
CodePudding user response:
The second argument to max
is an ordering function that extracts the value to order by. Thus, max(square, key = lambda k: square[k])
returns the key of square
that has the greatest corresponding value.
CodePudding user response:
In this instance, k is referring to the key in the dictionary square.
Dictionaries are made up of key:value pairs, which you can see in the declaration of square in the first line.
If we want a specific value from a dictionary, we need to reference it's key. So if we want to print 4 from our dictionary, we need to feed in the key 2.
So the following code would print '4':
square = {2: 4, -3: 9, -1: 1, -2: 4}
k = 2
print(square[k])