I am trying to understand how this works:
my_dict = {'a':2,'b':1}
min(my_dict, key=my_dict.get)
produces
b
Which is a really cool feature and one I want to understand better.
Based on the documentation
min(iterable[, key]) Return the smallest item in an iterable or the smallest of two or more arguments... The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).
Where can I find out more about available functions? In the case of a dictionary, is it all the dictionary methods?
Edit: I came across this today:
max(enumerate(array_x), key=operator.itemgetter(1))
Still looking for information on available keyword functions for min/max
Imagine you have objects with some attribute you want to use to get the minimum value:
This will give you the object with the smallest
something
attribute.The same thing exists for example in
sorted()
so you can easily sort by a value derived from the object. Imagine you have a list of people and want to sort by first name, then last name:The code you have written is
actually this works on
min
function. so, what does min do?The key here is used to pass a custom comparison function.
Example: output max by length of list, where arg1, arg2 are both lists.
But what if I want the max from the list, but by considering the second element of the tuple? here we can use functions, as given in official documentation. The
def
statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.
so the functions are basically depend upon the the iterable and and passing the criteria for the comparison.
Now in your example, you are iterating over your dictionary. And in key, you are using
get
method here.As here, no arguments are there in
get
method it simply iterates over values of dictionary. And thus themin
gives you the key having minimum value.For
max(enumerate(array_x), key=operator.itemgetter(1))
we want to compare the values of array instead of their indices. So we have enumerated the array.now we have used
itemgetter
function of operator module.operator.itemgetter(n)
constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.you can also use lambda function of here like
So the range of functions in
key
is almost up to the use. we can use many functions but the sole motive is , it is the criteria for that comparison.