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
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
i in d
work. isn't the d is dictionary , i thought we have to use d.iteritems() for that
Feb 20, 2013 at 9:23
for i in d.keys()
Feb 20, 2013 at 9:25
d
is the dict thats ok . now what is the function of key=d.get
i understand the d.get() gets the value stored at some key , but from where it gets its key
Feb 20, 2013 at 9:31
min
function calls key
to sort the iterable, and it returns the first element of the resulting list. The sorting method calls the function on each element of the iterable to sort them. This is just like how the map
and filter
function key
arguments work.
Feb 20, 2013 at 9:34
key
to sort. can you explain with code what happens during the call. you mean that min
function needs the key
so that it can get the values stored at that key so value becomes d.get(key). so after all the values are fe5tched , it then sorts them in ascending order and gives the first one oin the list. am i right??? so key=d.get
is tranlated to d.get(key)
for evry item to get the value there
Feb 20, 2013 at 9:41
key
ofd
where the functiond.get(key)
(equivalent tod[key]
) returns the lowest comparable value.min(d.values())
i am not getting what is the second arument used for. i mean how is the second argument related to first argumentlist.sort()
."min(d)
returns the minimum key, not the key with the minimum valuemin(d)
returnsa
in your case, becausea<b<f
, not because2<3<5
. Ford={'a':3,'b':2,'c':1}
,min(d)
returnsa
, butmin(d, key=d.get)
returnsc
(because1<2<3
).