Python, find variable/key based on maximum value -


i have several values, this:

value_a = 5 value_b = 10 value_c = 20 

i want find largest value , print name of value. use

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

but gives me value , not name.

instead of defining variable, need create dict map name value. need call max() operator.itemgetter() key it. example:

my_dict = {    'value_1': 10,    'value_2': 30,    'value_3': 20 }  operator import itemgetter  var_text, value = max(my_dict.items(), key=itemgetter(1))    # value of: # `var_text`: "value_2" # `value`: 30 

here, max() return tuple maximum value in dict.

if not care maximum value, , want key holding it, may do:

>>> max(my_dict, key=my_dict.get) 'value_2' 

explanation:

my_dict.items() return list of tuple in format [(key, value), ..]. in example gave, hold:

[('value_1', 10), ('value_3', 20), ('value_2', 30)] 

key=itemgetter(1) in satement tell max() perform max operation on index 1 of each tuple in list.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -