Solution Sharing

Same here… Glad to hear I’m not alone :wink:

Mine isn’t as long winded as some on here with only one for loop. But didnt know there was a max function till seen the solutions above.

def max_key(my_dictionary):
  max_key = 0
  max_value = 0
  for key, value in my_dictionary.items():
    if value > max_value:
      max_key = key
      max_value = value
  return max_key

max_key would be initialized as the key for the starting max_value.

max_value should be initialized to a value from the dictionary. What if all the values are less than zero?

>>> def max_key(my_dictionary):
	key_value_pairs = list(my_dictionary.items())
	max_key, max_value = key_value_pairs[0]
	for key, value in key_value_pairs[1:]:
		if value > max_value:
			max_key, max_value = key, value
	return max_key

>>> d = dict(zip(['a','b','c','d','e'],[33, 11, 55, 22, 44]))
>>> max_key(d)
'c'
>>> 
1 Like

My solution looks so simple compared to some others here.

def max_key(my_dictionary):
max_value = 0
for key, value in my_dictionary.items():
if value > max_value:
max_value = value
max_key = key
return max_key

I like this one. Really goes along with the lesson, instead of using other functions and methods I haven’t learned about!

Thanks!

1 Like
def max_key(my_dictionary):
    return max(my_dictionary, key=my_dictionary.get)
2 Likes
def max_key(my_dictionary):
  largest_value = 0
  key_associated = ""

  for key, values in my_dictionary.items():
    if values > largest_value:
      largest_value = values
      key_associated = key
  return key_associated

no max() solution

1 Like

Jeez! This is wayyyyyy easier. Thanks

Good job on a solution without max (not to say that using max isn’t a valid solution). I’d consider changing largest_value to something like float("-inf") so that negative numbers are also dealt with appropriately and adding to this code to catch all keys with an identical largest value which could be more effective than using max as you’d have to check the list a second time for repeated maximum values.

-inf has the same problems as 0 does, pick a key from the dict instead

(also not sure what you mean max is doing wrong, I don’t see it)

Mmm yeah you’re probably right any key would be a better shout, that’s actually much nicer.

I don’t think using max is incorrect, it’s a perfectly valid solution. My only issue with it is in a situation where more than one value shares the same maximum it’s only going to return a single key. You’d have to check through the dictionary again if you required every key corresponding to that maximum value.

Would you ever want multiple responses though? Isn’t the intent to return a key?

Maybe you mean doing max to get the max value, and then make a second scan. You don’t need to use max that way, you can run max on the keys, and let max look up the corresponding value and compare on that instead of the key itself.

> maximumOn abs [10, -100]
-100

Quick exmaple of what I meant. If we’re looking for the key corresponding to the maximum value the following example would arguably have three possible keys corresponding to the maximum value, keys=(‘b’, ‘c’, ‘e’). For the given function style you’d only get the first appearance (at least from 3.6 on). That might be fine if it’s any key with a maximum value you wanted but it’s still worth noting that you won’t get repeats without searching again.

def max_key(a_dictionary):
    return max(a_dictionary, key=my_dictionary.get)


example_dictionary = {'a': 2, 'b': 3, 'c': 3, 'd': 1, 'e': 3}
max_key(example_dictionary)  # would give you 'b' but not 'c' or 'e'

Right but you’d want to match max’s behaviour.
And if you didn’t, then you’d have to change the return type to return a list. This would be nice in that empty input becomes valid, but perhaps a bit less nice in that the result now has to be unboxed from the result list.

Here’s mine:


def max_key(my_dictionary):
  keys = list(my_dictionary.values())
  keys.sort()
  largest = keys[-1]
  for key in my_dictionary.keys():
    if my_dictionary[key] == largest: 
      return key
    else:
      continue

Not the smartest solution as I can see, but I think it does the job :smiley:

Can anyone tell me what I’m doing wrong? I am getting the output that the commented code tells me was expected, (1, c) but I get an error message telling me, " max_key({1:2, 2:3}) returned 2, expected 2."

Here’s my code:

def max_key(my_dictionary):
  max_val_key = ""
  biggest_val = float("-inf")
  for key, value in my_dictionary.items():
    if value > biggest_val:
      biggest_val = value
      max_val_key = str(key)
  return max_val_key

The only thing I changed after looking at the hint was adding “-inf” inside the float parenthesis. Prior to that, I just had float() there, but I am still getting the same response from the lesson regardless of that change. I could look at the solution, but sometimes I can’t infer what I was doing wrong by going that route. Please help!

Pretty much sets the bar right into the floor. Nice catch!

the float value representing negative infinity isn’t a great value to use as it isn’t some form of universal smallest value. for starters, it’s a number, there are other types that are orderable but aren’t numbers and those might either consider themselves smaller than negative infinity or not be comparable to floats at all.

you do however have a dict full of values that would be suitable, you could pick one of those instead. same with the key, you wouldn’t start with an empty string because there might not be such a key. use the key for the value you picked from the dictionary instead.

similarly, you shouldn’t convert the key to str as … either it is a str, and then it would be redundant, or it’s not a string, and then you would be using a different key than the one you found, because you converted it to something else

That was it! I removed the str() conversion on my variable re-assignment and the error went away! Thanks for the help!

The shortest solution to this question.

def max_key(my_dictionary):
sorted_List=sorted(my_dictionary.items(), key=lambda x: x[1])
return sorted_List[-1][0]