r/learnpython • u/Apart-Implement-3307 • Sep 08 '25
Explain This Code
students = {"Frank": 85, "Monica": 72, "Steve": 90} print(max(students, key=students.get))
Can you explain this code in simple terms or to 10 years old guy I can't understand this (key=students.get) Can you explain what is the purpose and use of (key=students.get) this.
0
Upvotes
32
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 08 '25 edited Sep 08 '25
Sure.
So,
maxtakes an iterable, and gives you whichever element had the highest value. The optionalkey-argument lets you tell it how to determine what value to use for comparison.In this case, as
studentsis a dictionary, a plain iteration over it gives you the names only. By usingstudents.getas the key,maxgives each string to that method call (which returns the corresponding integer), andmaxthen returns whichever dictionary key had the highest number.For example, this code would print "Steve", because
90is the highest of the three numbers.As a more practical demonstration, the program is essentially doing this, but more compact: