Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding minimum value in dictionary

I have a dictionary with grades. When I ask for the minimum value it gives me the largest value. I used the min(Grades) to find the minimum but it was me the largest then I found min(Grades.items(), key=lambda x:x[1]) and it worked but I don't get why the min(Grades) doesn't work. I also have no idea how the min(Grades.items(), key=lambda x: x[1]) works and what it means.

>>> Grades
{'pr': [17, 15], 'hw': [16, 27, 25], 'ex': [83, 93], 'qz': [8, 10, 5]}
>>> min(Grades)
'ex'
>>> min(Grades.items(), key=lambda x: x[1])
('qz', [8, 10, 5])
like image 583
joe van horn Avatar asked Aug 15 '26 23:08

joe van horn


1 Answers

Iterating dictionary yields keys, not (key, value) pairs.

>>> d = {'pr': [17, 15], 'hw': [16, 27, 25], 'ex': [83, 93], 'qz': [8, 10, 5]}
>>> list(d)
['pr', 'qz', 'hw', 'ex']

>>> min(_)
'ex'

min on the dictionary returns the key that is largest (lexicographically).


Meaning of min(Grades.items(), key=lambda x: x[1])

min accepts optional key parameter. The return value of the key function is used to compare order of items, instead of the original values.

The parameter x of the lambda is each item passed to the function. ('pr', [17, 15]), ('hw', [16, 27, 25]), ...; So the second items (x[1]) in the tuples are compared instead of the tuples.

like image 170
falsetru Avatar answered Aug 20 '26 04:08

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!