Dictionary with multiple maximum values
d = {
'a': 1,
'b': 2,
'c': 3,
'd': 3,
'e': 2
}
For, I want to process to get multiple keys ([c, d]
in this case)
From @shiracamus
Isn't it simpler not to use numpy?
by_shiracamus.py
d = {
'a': 1,
'b': 2,
'c': 3,
'd': 3,
'e': 2
}
#Find the key whose value is max
max_val = max(d.values())
keys_of_max_val = [key for key in d if d[key] == max_val]
print(keys_of_max_val)
beautiful!
keys_of_max_val = [key for key, val in d.items () if val == max_val]
I like the look, but what about the speed ...
Let's check it even in your free time ...
import numpy as np
d = {
'a': 1,
'b': 2,
'c': 3,
'd': 3,
'e': 2
}
#Get key with ndarray
keys = np.array([a[0] for a in d.items()])
#Get value with ndarray
values = np.array([a[1] for a in d.items()])
#Find the key whose value is max
keys_of_max_val = keys[values == values.max()]
print(keys_of_max_val)
I'm not used to the inclusion notation!
['c' 'd']
When there is only one maximum value
key_of_max_val = max(d.items(), key=(lambda x: x[1]))[0]
Even though you can get it with, if there are many maximum values, it will become troublesome as soon as possible.
Recommended Posts