joe van horn
joe van horn

Reputation: 61

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])

Upvotes: 3

Views: 12169

Answers (3)

Kerry Kobashi
Kerry Kobashi

Reputation: 801

Try this.

minScore = 100
lowInitial = ""
grades = {'pr': [17, 15], 'hw': [16, 27, 25], 'ex': [83, 93], 'qz': [8, 10, 5]}
for initials, scores in grades.items():
    lowestScore = min(scores)
    if lowestScore < minScore:
        minScore = lowestScore
        lowInitial = initials
print("Person with lowest score is: " + lowInitial)
print("Lowest score was: " + str(minScore))

Person with lowest score is: qz
Lowest score was: 5

Upvotes: 1

Joe T. Boka
Joe T. Boka

Reputation: 6585

You can also find the key with the min values using dictionary comprehension

d = {k for k,v in grades.items() if v == min(grades.values())}

Output:

set(['qz'])

Upvotes: 0

falsetru
falsetru

Reputation: 369054

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.

Upvotes: 3

Related Questions