Instead of defining variable, you need to create a dict
to map the name with the value. Then you need to call max()
with operator.itemgetter()
as key
to it. For example:
my_dict = {
'value_1': 10,
'value_2': 30,
'value_3': 20
}
from operator import itemgetter
var_text, value = max(my_dict.items(), key=itemgetter(1))
# Value of:
# `var_text`: "value_2"
# `value`: 30
Here, max()
will return the tuple with maximum value in the dict
.
If you do not care about the maximum value, and you just want the key
holding it, you may do:
>>> max(my_dict, key=my_dict.get)
'value_2'
Explanation:
my_dict.items()
will return list of tuple in the format [(key, value), ..]
. In the example I gave, it will hold:
[('value_1', 10), ('value_3', 20), ('value_2', 30)]
key=itemgetter(1)
in the satement will tell max()
to perform the max operation on the index 1
of each tuple in the list.