# Write your max_key function here:
def max_key(my_dictionary):
largest_key = float("-inf")
largest_value = float("-inf")
for key, value in my_dictionary.items():
if value > largest_value:
largest_value = value
largest_key = key
return largest_key
can anyone please explain this code
What part about it is confusing? Is it the float("-inf")
part or the whole function?
Break it down into smaller pieces and talk it out.
A dictionary in python is comprised of {key: value, key: value}
You’re writing a function where you want to return the largest key
in a dictionary.
First, what does this part do?
largest_key = float("-inf")
largest_value = float("-inf")
This might be of some help. If all else fails use Google:
https://stackoverflow.com/questions/34264710/what-is-the-point-of-floatinf-in-python
And this:
https://www.geeksforgeeks.org/python-infinity/
Then ask yourself, what does this for
loop do? What does the .items()
method do with a dictionary?
for key, value in my_dictionary.items():
May be you don’t undertand what
largest_key = float("-inf")
exactly means. You can think about that this way:
For each number n you can choose is True:
float("-inf") < n.
So in this way of thinking largest_key = float("-inf") is initialization of sorting exactly the same way we initialize summarize with sum = 0, or multiplication with mult = 1.