Skip to content
Advertisement

How to drop dictionaries with NaN values from list

This seems like a fairly simple thing but I haven’t been able to find an answer for it here (yet).

I have a list of dictionaries, and some of the dictionaries in the list have NaN values. I just need to drop any dictionary from the list if it has a NaN value in it.

I’ve tried it a few different ways myself. Here’s one attempt with filter and a lambda function, which got a TypeError (“must be real number, not dict_values,” which makes sense):

JavaScript

I also tried it with a couple nested loops and some code I really wasn’t sure about and got the same error:

JavaScript

… and finally with just a list comprehension (same error):

JavaScript

EDIT:

Here’s a sample of the list I’m working with:

JavaScript

Advertisement

Answer

dictionary.values() is a generator for all the values in the dictionary. You need to call math.isnan() on the individual values. You can use any() to do this:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement