mardi 18 août 2020

insert np.nan into dictionary elements using dictionary comprehension

I would like to know how to replace elements of a dictionary that don't meet a condition. For example, I want to replace all elements of the dictionary that don't equal 2 with nan:

test = {'a': [1,2,3,4], 'b': [2,3,4,5]}

I'm using the following code:

test2 = {name: item if item == 2 else np.nan for name in test.keys() for item in test[name]}

I would like the following answer:

test2 = {'a': [nan, 2, nan, nan], 'b': [2, nan, nan, nan]}

Instead, I am getting:

test2 = {'a': nan, 'b': nan}

I'm not sure where I'm going wrong?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire