Solution Sharing

The thing to bear in mind is the maximum number iterations necessary to complete this task. It is not necessary to do any sorting. That just adds to the complexity.

Spoiler
>>> def max_key(d):
	key = [*d.keys()][0]
	val = d.get(key)
	for k, v in d.items():
		if v > val:
			key, val = k, v
	return key, val

>>> a = {'one': 1, 'two': 2, 'three': 3}
>>> max_key(a)
('three', 3)
>>> 

Rabbit Hole
>>> def max_key(d):
	try:
		key = [*d.keys()][0]
		val = d.get(key)
		for k, v in d.items():
			if v > val:
				key, val = k, v
		return key, val
	except IndexError:
		return "Empty dictionary, perhaps?"
	except:
		return "Fatal Error!"

	
>>> max_key({})
'Empty dictionary, perhaps?'
>>> max_key(n)
'Fatal Error!'
>>> max_key(a)
('three', 3)
>>> 

So many ways.

def max_key(my_dictionary):
	def second(elem):
		return elem[1]
	lst = sorted(list(my_dictionary.items()), key=second)
	return lst[-1][0]

Very elegant solution!

Unless I’m mistaken, your solution is actually more efficient that the one by prosowski because it only calls .values() once, instead of calling it once for each item in my_dictionary. Granted, I don’t think .values() is very “expensive”.

I saw many different ways of doing this task, this is mine:

def max_key(my_dictionary):

  max_value = 0

  for i, j in my_dictionary.items():

    if j > max_value:

      max_value = j
      key_max_value = i

    else:
      continue

  return key_max_value

What if all the values are negative?

Love seeing so many solutions

def max_key(my_dictionary):
largest_key= “”
largest_value= -100000
for key in my_dictionary.keys():
if my_dictionary[key] > largest_value:
largest_value= my_dictionary[key]
largest_key = key
return largest_key

Welcome to the forums!

I would suggest that you initially set largest_value to the first value in the dictionary (what if all the values in the dictionary were under -100000?).

Additionally, you can use the .items() method on the dictionary instead of the .keys() method. This would allow you to more directly access the values rather than finding the corresponding value to a key.

1 Like
def max_key(my_dictionary):
  max = list(my_dictionary.keys())[0]
  for key in my_dictionary:
    if my_dictionary[max] < my_dictionary[key]:
      max = key
  return max
def max_key(my_dictionary):
  values = []
  largest_key = float("inf")
  for value in my_dictionary.values():
    values.append(value)
  values.sort()
  largest_value=values[-1]
  for key, value in my_dictionary.items():
    if value == largest_value:
      largest_key = key
  return largest_key

Looks great! Here are two things to possibly consider:

  1. Instead of setting largest_key to infinity, None might be a good option.
  2. How could you solve this challenge by only iterating through the dictionary once rather than twice?

I thought we should practice loops instead of using methods so my solution is this:

# Write your max_key function here:
def max_key(my_dictionary):
  v, k = 0, 0
  dickeys = list(my_dictionary.keys())
  for i in dickeys:
    x = my_dictionary.get(i)
    if x > v:
      v = x
      k = i
  return k

I thought its short and sweet until i saw 10 char long solutions here :slight_smile:

1 Like

The solution you arrive at on your own intuition is the one to feel proud of. Never mind what abstract approaches others are showing. Half of them are copied and pasted and not original to the poster. Work with the basics as much as you can and with time and practice you will discover the why’s and how’s of refactored approaches.

I should of have replied earlier, but didnt wanna spam the thread with “thx” message. Nonetheless, I actually think about what you said when I have trouble understanding something. I keep working on it, and I really do feel proud when I get to a conclusion by myself. I am now on lectures about Methods and inheritance and its not so easy to understand as the previous lectures. Anyway, thank you for your reply.

1 Like

This one had me stuck for a bit. Had to sleep on it.
Here’s the solution I came up with:

def max_key(my_dictionary):
  key_lst = [0]
  val_lst = [0]
  for key,value in my_dictionary.items():
    if value > val_lst[0]:
      val_lst[0] = value
      key_lst[0] = key
  return key_lst[0]

Hello, @corepro68806.

What is your reasoning behind using lists: key_lst, val_lst?

I am able to create the required dictionary pairs separately in each list. Once each list has been created, I can then zip the lists together creating the dictionary the prompt requires.

You aren’t doing any of that. Your lists only ever contain a single element at a time. Seems a variable would suffice. No?

Oh shoot, you’re right, I was thinking of a future prompt.
My concern for using variables was variable types.

If there are different key types, such as a string or integer, then I was worried that I’d run into an issue predefining the variable so that it could be returned outside of the if statement.

Python isn’t strongly typed, so you could initialize your max_key to an empty string, or 0 or even None. Probably None would be most appropriate, but all of them would work.

You’d run into problems if your were comparing keys, but you only need to compare the values, and remember the key associated with the max value. You could have a dictionary where some of the keys are strings and some are ints, and it would make no difference.

1 Like