A key in a nested dictionary if it contains a NaN value?
I have the 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 is in finding the key that has the maximum C value. So far, good working code works, but it doesn't give correct results if "c" is NaN like in my case? I wrote the following code
max(my_dictionary, key=lambda v: my_dictionary[v]['c'])
what change do I need in the above code to account for NaN values ββin C?
+3
source to share
1 answer
You can provide a default value for NaN:
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 a key instead of looking up the value twice and use Number
to handle the case when 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))
+3
source to share