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
2
u/bio_ruffo Sep 08 '25
Ok, in order:
If you read the docs for the max() built-in function, the first argument can be an iterable, and then `key` is an optional argument that specifies a function that should apply to the data. So `students` is used as an iterable and `students.get` is the function to apply to it.
if you iterate over a dictionary, by default you iterate over the dict's keys, so you're iterating over the names.
the .get() method of the dictionary will return, for each key (person's name), its corresponding value (the number, 85, 72 or 90), and these values will be used to order the data and pick the maximum one.
So in a pinch, with this code you're getting the name that corresponds to the highest number.
Alternatives that do the same thing, just written differently:
max(students, key=lambda x: students.get(x))
max(students, key=lambda x: students[x])