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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With