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'}