Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why will python function max() return different outputs if float('NaN') value is permuted in a dictionary but key-max_value remains the same?

Let’s pretend I have the following simple dictionary:

dictionary = {'a':3, 'b':4, 'c':float('NaN')}

If I use function max() to return the key with maximum value…

key_maxvalue = max(dictionary, key=dictionary.get)
print(key_maxvalue)

…python outputs this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b

However, when I permute the values of keys ‘a’ and ‘c’…

dictionary = {'a':float('NaN'), 'b':4, 'c':3}
key_maxvalue = max(dictionary, key=dictionary.get)
print(key_maxvalue)

…I get this unexpected result:

a

I expected python would output ‘b’, as that key still has the maximum value in the dictionary. Why has a change in the values order altered the function max() output? Furthermore, how could I prevent this (unexpected) event from happening?

>Solution :

If you wrote your own function, it might look like this:

def max(nums):
    largest = nums[0]

    for item in nums:
        if item > largest:
            largest = item

    return largest

The problem is this comparison item > largest. Look what happens when you compare a number with np.nan.

Input: np.nan > 4

Output: False

Input: 4 > np.nan

Output: False

Any comparison with a NaN will be False. If max functions like our written function, then it happens what happens in both of your cases. It’s not larger than 4, so b is still the max. However, when it defaults to a in the second case, no other number is larger than NaN, so a remains the max.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading