1

I have searched for ways of grabbing an associated key based on a value, but most seem very complicated. It may be because I'm new at Python, but is there an easy way to get a key associated with a (max) value? For example:

d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
max(d.values())

will give 5.

How do I get the key associated with that value of '5'?

Isaac
  • 1,442
  • 17
  • 26
magic9669
  • 39
  • 1
  • 3
  • Duplicate? http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary –  Jan 29 '17 at 02:48
  • Possible duplicate of [Get key by value in dictionary](http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) –  Jan 29 '17 at 05:21

1 Answers1

0

You could iterate through the dictionary and save the key of the highest value.

import math

max_value = -math.inf  # Infinitly small number.
max_value_key = None
for key, value in d.items():
    if max_value < value:
        max_value = value
        max_value_key = key
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • I tried that but couldn't get it to work. I found a solution on here from another user, but I truly don't understand how it works: maximum = max(d, key=d.get) print(maximum, d[maximum]) So with my example, this would return the 5 value since it's the max, and will return the key associated with 5, that being 'five.' If I were to break down the solution, and just do maximum = max(d), it will return 'two'. I guess I'm not understanding the get method? I don't know, i'm so confused trying to break this down to understand it... – magic9669 Jan 29 '17 at 15:16
  • Just print `max_value_key` and you'll see this method works. `maximum = max(d, key=d.get)` is better though. The key option is a function each element in `d` is passed into. The elements in `d` are the keys and `d.get` will return the value of each key. So `max(d, key=d.get)` will see which key in your dictionary which have the greatest value and give you the corresponding key. When you do `max(d)` you're looking for the greatest key in the dictionary, and since they all are strings it'll give you the string which is greatest in alphabetical order. – Ted Klein Bergman Jan 29 '17 at 15:47