Home > Back-end >  How do I delete nan-valued keys from one dictionary into another dictionary
How do I delete nan-valued keys from one dictionary into another dictionary

Time:01-21

I have this dictionary :

d = {4: {0: [12], 1: [194]}, 8: {0: [222], 1: nan}, 18: {0: [60], 1: nan},
      19: {0: [128], 1: nan}, 21: {0: [54], 1: nan}}

the output should look like this:

  d = {4: {0: [12], 1: [194]}, 8: {0: [222] }, 
       18: {0: [60] }, 19: {0: [128]}, 21: {0: [54]}}

CodePudding user response:

You can recursively pass the dictionaries to a function that filters out key with nan values. For example:

from math import nan

d = {4: {0: [12], 1: [194]}, 8: {0: [222], 1: nan}, 18: {0: [60], 1: nan},
     19: {0: [128], 1: nan}, 21: {0: [54], 1: nan}}

def clean_nan(d):
    if isinstance(d, dict):
        return {k: clean_nan(v) for k, v in d.items() if v == v}
    return d

clean_nan(d)

Gives the result:

{4: {0: [12], 1: [194]},
 8: {0: [222]},
 18: {0: [60]},
 19: {0: [128]},
 21: {0: [54]}}

This assumes the lists don't contain nan, but if they did it would be easy to add another clause to filter those.

  •  Tags:  
  • Related