Solution Sharing

It always amazes me that people can figure out ways to solve challenges like these in like, 2 lines. I struggled with this one a bit and got it marked as solved by just copying one of the solutions from here, but in the end this is what I came up with on my own:

def max_key(d):
    highest = 0
    high_key = None
    for key in d.keys():
      if d[key] > highest:
        highest = d[key]
        high_key = key
    return high_key

Another solution without using max() or initialising a key:

def max_key(my_dictionary):
  max_val = 0 
  for key in my_dictionary.keys():
    for value in my_dictionary.values():
      if value > max_val: 
        max_val = value
    if my_dictionary[key] == max_val:
        return key

Could one not simplify from 3 lines to 2 with:

def max_key(my_dictionary):

  return max(my_dictionary, key=my_dictionary.get)

And in so doing avoid the need for a lambda function?

Thank you @mtf for bringing to my attention that my solution could be better. I have reviewed my answer and re-posted.
Thank you for your work!

# Return key for the maximum value in dictionary
def max_key(my_dict):
    m_key = ""
    for key,value in my_dict.items():
        if m_key == "":
            m_key = key
        else:
            if value > my_dict[m_key]:
                m_key = key
    return m_key

        
# Test area
test_dict = {"A":0, "B":1, "C":2, "x":34, "r":21, "t":56, "s":28, }
test_dict_2 = {"A":0, "B":-1, "C":-2, "x":-34, "r":-21, "t":-5.6, "s":-28, }
print(max_key(test_dict_2))
1 Like

Another slightly different one.

I know one downside of this fuction is not being able to handle values < 0 which will probably take some thought…

def max_key(my_dictionary):
  max_value = 0
  for x, y in my_dictionary.items():
    if y > my_dictionary.get(max_value,0):
      max_value = x
  return max_value
from random import randint
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b = [randint(1, 100) for _ in a]
c = dict(zip(b, a))    # up to 26 keys, but may be less
>>> max_key(c)
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    max_key(c)
  File "C:/Users/Mr/AppData/Local/Programs/Python/Python38/Scripts/users/max_key_jasonhowling.py", line 4, in max_key
    if y > my_dictionary.get(max_value,0):
TypeError: '>' not supported between instances of 'str' and 'int'
>>> 

wanted to accomplish the task without the help of any built-in function (except dictionary ones).
How can I set my biggest_value to int ver. of None so that it can also handle (-)ve values ?

def max_key(my_dictionary):
  biggest_key = 0
  biggest_value = 0
  for key, value in my_dictionary.items():
    if value > biggest_value:
      biggest_value = value
      biggest_key = key
    else:
      continue
  return biggest_key

My code! I like it, I think it could be more simplified but whatever.

def max_key(my_dictionary):
  max_value = max(my_dictionary.values())
  for key in my_dictionary.keys():
    if my_dictionary[key] == max_value:
      return key

What is the objective of this exercise? Is it to find the largest value and return it’s key? Or is it to find the largest key?

It is to find the largest value and return it’s key.

Given we already know the max value, we cannot really simplify what you have since it looks for the key associated with that value and immediately returns it.

For s&g can you solve this without relying on the .values() and .keys() methods?

Maybe I could use .items()?

That would be more of the same. What if we leave that one out, too? Think in terms of iterating the dictionary in the normal sense.

Maybe something like:

for thing in my_dictionary:
  max_value = max(thing[0][0])
  if thing[0][0] > max_value:
    max_value = thing[0][0]
  if thing[0] = max_value:
    return thing[0]

This is off the top of my head.

In the above, thing is the key, right? Does a key have a numeric subscript?

Oh I was thinking that thing would represent the individual key: value pairs in my_dictionary. And I’m not really sure what a numeric subscript is?

thing[0]

It looks more like a list index than a dict subscript (mind keys can be numbers, a special case).

I see, so after running this code:
for thing in my_dictionary:

  for thing in my_dictionary:
    print(thing)

I do get the keys. So maybe something like this instead?

for thing in my_dictionary:
  max_value = max(my_dictionary[thing])
  if my_dictionary[thing] > max_value:
    max_value = my_dictionary[thing]
  if my_dictionary[thing] = max_value:
    return thing

When there is but one value, is it not its own maximum?

Oh yes, and now looking at it I’m not using .values(), so I wouldn’t really need to use max.

for thing in my_dictionary:
  max_value = my_dictionary[thing]
  if my_dictionary[thing] > max_value:
    max_value = my_dictionary[thing]
  if my_dictionary[thing] == max_value:
    return thing