Help with dictionaries

Hey fellas, how you all guys doing? I hope you are great!

I need some help with dictionaries in Python, I am doing the exercises in the platform and there was one excersie that I could not solve, I look up the “Solution” but I did not understand it.

Here is the link:
https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-dictionaries-cc/exercises/largest-value

I do not understand why the largest_value = float("-inf")? Why the ("-inf")?

Is that a rule for this kind of exercises?

Thanks for the help!

-inf or float("-inf") is just a Python value that has the property that -inf < x returns True for any x. (Likewise, inf > x returns True for any x.)

It can be used if your algorithm (problem-solving strategy) reguires such a value, perhaps as a first step in sorting or finding a maximum value.

So the property float("-inf") is for negative numbers and “inf” is for positive ones?

float("-inf") evaluates to negative infinity, which is a value that is smaller than any finite number, and float("inf") evaluates to infinity, which is a value that is larger than any finite number.

The hint asks you to do this:

  largest_value = float("-inf")
  largest_key = ""

That is so that regardless of how small any of the values are in my_dictionary, we can ensure from the start that largest_value does not exceed the largest value there. Subsequently, we can compare, iteratively, each value we encounter to whatever is, thus far, the largest value we have found.

The code recommended by the hint will produce correct output for the test function calls that are provided at the bottom of the script. However, we need to look more critically at it.

Consider this portion of the hint:

Any time you find a value larger than what is currently stored in largest_value , replace largest_value with that new value. Similarly, replace largest_key with the key associated with the new largest value.

That recommendation suggests that we use this if header:

    if my_dictionary[key] > largest_value:

However, the above is inadequate for handling a particular special case that we could contrive. Can you figure out what that special case would be?

1 Like