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

remove keys from dict based on value example nan

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:

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

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

>Solution :

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