Key Corresponding To Maximum Value In Python Dictionary
Solution 1:
The dictionary "a" is an iterable structure in python. When you loop through with for x in a
, you are looping over the keys in the dictionary.
In the second line, the max function takes two arguments: An iterable object (a), and an optional "key" function. The Key function is going to be used to evaluate the value of the items in a--the largest of which will be returned.
Examples:
>>>a = dict(((1,3),(0,-1),(3,21)))>>>for x in a:...print x #output the value of each item in our iteration...
0
1
3
Note here that only the "keys" are output. When we pass each of these keys to "get"...
>>>a.get(0)
-1
>>>a.get(1)
3
>>>a.get(3)
21
We get the value for each key. Now see how max works.
>>>b=[2, 3, 5, 6, 4]>>>max(b)
6
>>>definverse(x):...return1.0 / x...>>>max(b, key=inverse)
2
As you can see, max (by default) will just find the largest number in our iterable list. If we define the "inverse" function, it will return the largest item in b for which inverse(item)
is the largest.
Combine these two items and we see that max(a, key=a.get)
is going to return the item
in a
for which the value of a.get(item)
is largest. i.e. the key corresponding to the largest value.
Solution 2:
Are you asking how the key
parameter works? It takes a callable, which is applied to every element in the dictionary. In the case of your dictionary, it simply does this:
a.get(1) # 3
a.get(0) # -1
a.get(3) # 21
max
then uses the result of the key function as the comparison value, so it will obviously choose the element which returns the highest value, ie 3.
Post a Comment for "Key Corresponding To Maximum Value In Python Dictionary"