user192082107
user192082107

Reputation: 1367

how does the python min function works

I was reading the question where the desired output was to get the element with minimum value

so if

d= {'a':2,'b':3,'f':5}

The answer is a

The answer given is min(d, key=d.get)

can anyone explain how this works

Upvotes: 4

Views: 4936

Answers (1)

Volatility
Volatility

Reputation: 32308

The min function returns the minimum value of an iterable according to the given key. In this case it returns the key of d with the minimum value. d.get allows you to access the corresponding value to the dictionary key, which are iterated over when you iterate over d.

For example:

>>> min([3, 5, 2, 1, 5])
1
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for i in d:
...     print i
b
c
a
>>> d.get('b')
2
>>> d.get('d')  # Nothing is returned
>>> min(d, key=d.get)
'a'

The key argument to the min specifies what key you want to find the minimum on.

For example:

>>> min(['243', '172344', '6'])
172344
>>> min(['243', '172344', '6'], key=len)
6

The min function does something like this:

>>> min(['243', '172344', '6'], key=len)
# sort the list with key (call `len` on every element and sort based on that)
# sorted(['243', '172344', '6'], key=len)
# return the first element (lowest value)
# sorted(['243', '172344', '6'], key=len)[0]
6

Upvotes: 4

Related Questions