How to find out which var has the highest value and return the var name in python

Viewed 29

I have a list of numbers and I want to find the var with the highest value but I don't want to use max() because I want the program to return the variables name with the highest value, not the value. Example code:

var1=0
var2=1
var3=2
list[var1,var2,var3]
2 Answers

This is a strange requirement to the variable name :), You can use globals for this.

In [1]: var1=0
   ...: var2=1
   ...: var3=2

In [2]: d = {k:i for k,i in globals().items() if isinstance(i, int)}

In [3]: d
Out[3]: {'var1': 0, 'var2': 1, 'var3': 2}

In [4]: max(d, key=d.get)
Out[4]: 'var3'
var1=0
var2=1
var3=2
l = [var1,var2,var3]
max_val = l.index(max(l))
my_var_name = [ k for k,v in globals().items() if v == l[max_val]]
my_var_name
Related