开发者

key corresponding to maximum value in python dictionary

a = dict(((1,3),(0,-1),(3,21)))
m = max(a, key=a.get)

Can someone give me an explanation on why this returns the key corresponding to the maximum value开发者_JS百科? It's stumped me for quite a while. Thanks!


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
>>> def inverse(x):
...     return 1.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜