简体   繁体   中英

key in nested dictionary if it contains NaN value?

I have following data in python

my_dictionary = {
      'key1': {'a': 1, 'b': 1, 'c': 10}, 
      'key2': {'a': 1, 'b': 1, 'c': 'NaN'}, 
      'key3': {'a': 1, 'b': 1, 'c': 12}
       ...
       ...
}

My Interest in to find key that has max value of C. So far so good following code is working but it does not give correct results if 'c' has NaN value as in my case? I wrote following code

max(my_dictionary, key=lambda v: my_dictionary[v]['c'])

what change I require in above code to account for NaN values in C?

You could give a default value for the NaNs:

print(max(my_dictionary, key=lambda v: my_dictionary[v]['c'] 
     if isinstance(my_dictionary[v]['c'],int) else float("-inf")))

You can also use a function to pass as the key instead of looking up the value twice and use Number to handle the case where you have more than just ints:

from numbers import Number
def key(x):
    val = my_dictionary[x]['c']
    return  val if isinstance(val, Number) else float("-inf")
print(max(my_dictionary, key=key))

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