Reputation: 4291
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?
Upvotes: 3
Views: 806
Reputation: 180481
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))
Upvotes: 3