Decipher it step by step, from the inside outwards:
d.values()
gets you a list (in Python 2) of values of your dictionary. That is, the grades themselves.
The highest value is then obtained:
max(d.values())
Then, the index (position) is found in the list of values for that highest value:
d.values().index(max(d.values()))
That index applies to the list of values, but also to the list of keys. So you can use that index to find the key (student name) related to the highest value, and index that list (d.keys()
) with it:
d.keys()[d.values().index(max(d.values()))]
And thus, the result is the name of the person with the highest grade.
A clearer variant is to split it up into multiple lines:
grades = d.values()
maxgrade = max(grades)
maxindex = grades.index(grades)
names = d.keys()
maxname = names[maxindex]
Why your attempt failed:
I tried sorting d and print d.keys()[-1] but [got an error message:]
AttributeError: 'list' object has no attribute 'keys'
When you sort a dictionary, the result is a sorted list of just the keys: you lose the dictionary information. So after d = sorted(d)
, d
is now a list
, and does not have a method, or more generally, attribute, keys()
. Hence the error message.
As to how to do this properly, refer to this question. In particular, the clearest answer there is
max(d, key=d.get)
The max
function can take a key
argument, and using d.get
will actually use whatever d.get
returns (which are the values, not the keys) to find the maximum.
You could use the same with sorted
:
sorted(d, key=d.get)
will list the names, ordered from lowest to highest grade.