0

how can I delete the keys in a dictionary that has values nan ? with and without creating new dictionary ?

example:

my_dictionary = dict(
    first=float("nan"),
    second="second"
)

expecting:

{'second': 'second'}
{k:v for k,v in my_dictionary.items() if not isnan(v)} 

does not work because isnan(v) takes only number as parameter

harveeey
  • 41
  • 7

2 Answers2

1

Perhaps you can use a dict comprehension using the fact that NaN is not equal to NaN:

out = {k:v for k,v in my_dictionary.items() if v==v}

or using math.isnan:

out = {k:v for k,v in my_dictionary.items() if not isinstance(v, float) or not math.isnan(v)}

Output:

{'second': 'second'}
0

I provide two ways.

First way is to use a condition value==value. Interestingly, NaN==NaN returns False (I know it is confusing!). I used this NaN's characteristics. (FYI, see What is the rationale for all comparisons returning false for IEEE754 NaN values?)

Second way is to check if value type is not float. Even thought its type is float, it will check second condition weather it is NaN or not using math module. The reason I used two condition here is math.isnan() can only get number type, otherwise it throw an exception.

import math

my_dictionary = dict(
    first=float("nan"),
    second="second"
)
print(my_dictionary)  # before
#{'first': nan, 'second': 'second'}

# Way 1
my_dictionary = {k: v for k, v in my_dictionary.items() if v == v}

# Way 2
my_dictionary = {k: v for k, v in my_dictionary.items() if (not isinstance(v, float)) or (not math.isnan(v))}

print(my_dictionary)  # after
#{'second': 'second'}
Park
  • 2,446
  • 1
  • 16
  • 25