r/learnpython • • 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

12 comments sorted by

View all comments

3

u/Timmy_PAYNE Sep 08 '25 edited Sep 08 '25

max(students) would return the key which is highest in alphabetical order, cause it only compares the keys themself.

By adding the argument key=students.get, you define what is being compared by, the values of the dictionary. The function compares the student values(the dictionary values) but still returns the corresponding key - here ‚Steve‘

I hope that helps

official documentation

4

u/nekokattt Sep 08 '25

max(students) would return the keys, not the values...

3

u/Timmy_PAYNE Sep 08 '25

Youre right i mixed it up in my memory, my bad. I will edit my previous post to not spread my mistake

3

u/nekokattt Sep 08 '25

no problem, easily done