ukbaz
ukbaz

Reputation: 547

How to remove nan values from a dictionaries list of values in python 3?

Hi I have a list of dictionaries, each dictionary has a list of values. In that list there are nan values which I wish to remove. Here is an example dictionary;

temp = {'A': ['field1', 'field2', 'field3', np.nan, np.nan], 'B': ['field1', 'field2', 'field3', 'field4', np.nan]}

which looks like;

{'A': ['field1', 'field2', 'field3', nan, nan], 'B': ['field1', 'field2', 'field3', 'field4', nan]}

I desired output is :

{'A': ['field1', 'field2', 'field3'], 'B': ['field1', 'field2', 'field3', 'field4']}

I've tired the following with no success;

res = {k:v for k,v in temp2.items() if v is not np.nan}

Any help is appreciated

Upvotes: 2

Views: 3007

Answers (1)

mrCarnivore
mrCarnivore

Reputation: 5078

You are comparing the whole value (v in your case) with np.nan, but only single elements of the value of the dictionary are np.nan. You want:

res = {k:[elem for elem in v if elem is not np.nan] for k,v in temp.items()}

Upvotes: 6

Related Questions