简体   繁体   中英

How do I delete nan-valued keys from one dictionary into another dictionary

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM