Keyword functions for Python min/max
Asked Answered
H

2

5

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

Hillside answered 8/4, 2016 at 14:41 Comment(0)
A
6

The code you have written is

my_dict = {'a':2,'b':1}
min(my_dict, key=my_dict.get)

actually this works on min function. so, what does min do?

min(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its lowest item. With two or more arguments, return the lowest argument.

The key here is used to pass a custom comparison function.

Example: output max by length of list, where arg1, arg2 are both lists.

>>>> max([1,2,3,4], [3,4,5], key=len)
[1, 2, 3, 4]

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.

>>> max(l, key = lambda i : i[1])
(1, 9)

# Or

>>> import operator
>>> max(l, key = operator.itemgetter(1))
(1, 9)

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.

The method get() returns a value for the given key. If key is not available then returns default value None.

As here, no arguments are there in get method it simply iterates over values of dictionary. And thus the min 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.

enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that will return (0, thing[0]), (1, thing1), (2, thing[2])

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

max(enumerate(array_x), key=lambda i: i[1])

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.

Anthea answered 14/6, 2017 at 11:13 Comment(3)
What's ´l´? When do you declare ´l´? Is it a list of tuples? Where one of them is (1, 9)? Or what's going on?Keratose
@Keratose The 'l' here is a list of tuples with (1,9) one of the element in it.Anthea
here's a nice tutorial on the key parameter (new in Python 2.4) wiki.python.org/moin/HowTo/Sorting#SortingbykeysHillside
F
1

Imagine you have objects with some attribute you want to use to get the minimum value:

min(my_objects, key=lambda x: x.something)

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:

people.sort(key=lambda x: (x.first_name, x.last_name))
Freedwoman answered 8/4, 2016 at 14:43 Comment(1)
As far as i can tell, my question is not directly related to lambda functions (though I understand that a lambda could be used as a keyword function).Hillside

© 2022 - 2024 — McMap. All rights reserved.