简体   繁体   中英

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? 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. ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM