简体   繁体   中英

Get rid of NaN as key in python dictionary

I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:

from math import isnan

clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)

but the clean_dict is not a dictionary. I want to output it from python, but I get ''

filter doesn't return a dictionary. It returns a list in Python 2 and a filter object in Python 3.

You can use dict.pop :

d = {'a': 1, 'b': 2}
print(d)
# {'a': 1, 'b': 2}
d.pop('b')
print(d)
# {'a': 1}

And in your specific case,

dict_HMDB_ID.pop(float('NaN'))

For the sake of completeness. it could be done with a dictionary comprehension but there is no point in iterating since keys are unique anyway

clean_dict = {k: v for k, v in dict_HMDB_ID.items() if not math.isnan(k)}


If you insist on using filter here (you really shouldn't ) you will need to:

  1. pass it dict_HMDB_ID.items() so it will keep the original values
  2. provide a custom function because it will now operate on (key, value) tuples.
  3. transform the returned filter object (it will contain an iterator with (key, value) tuples) back to a dictionary


import math

dict_HMDB_ID = {1: 'a', float('Nan'): 'b'}
clean_dict = dict(filter(lambda tup: not math.isnan(tup[0]), dict_HMDB_ID.items()))
print(clean_dict)
# {1: 'a'}

I should probably mention that the first approach ( .pop ) directly modifies the dict_HMDB_ID while the other two create a new dictionary. If you wish to use .pop and create a new dictionary (leaving dict_HMDB_ID as it is) you can create a new dictionary with dict :

d = {'a': 1, 'b': 2}
new_d = dict(d)
new_d.pop('b')
print(d)
# {'b': 2, 'a': 1}
print(new_d)
# {'a': 1}

you could do:

from math import nan
dict_HMDB_ID.pop(nan)
clean_dict = dict_HMDB_ID

or the other way around if you wna to preserve dict_HMDB_ID

from math import nan
clean_dict = dict(dict_HMDB_ID)
clean_dict.pop(nan)

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