1

I have several values, like this:

value_a = 5
value_b = 10
value_c = 20

I want to find the largest value and print the NAME of the value. normally I would use

val = [value_a, value_b, value_c]
print max (val)

but this only gives me the value and not the name.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Shifu
  • 2,115
  • 3
  • 17
  • 15

4 Answers4

7

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

How about this. :)

In [1]: the_dict = {'value_a':5, 'value_b':10, 'value_c':20}

In [2]: max(the_dict, key=the_dict.get)

The output:

Out[2]: 'value_c'
Tanmaya Meher
  • 1,438
  • 2
  • 16
  • 27
1

You need to use dictionary or named tuple. Example using dictionary is below

Python 3.4.3 (default, Sep 14 2016, 12:36:27) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> vdict={'value_a':5,'value_b':10,'value_c':20}
>>> max(vdict, key=vdict.get)
'value_c'
>>> 
Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
0

Make a dictionary for the values and then simply call this function in the print statement.

values = {
   'value_1': 10,
   'value_2': 30,
   'value_3': 20
}

print (max(values, key=lambda i: values[i]))

Output:

value_2
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44