# Solution Sharing

Ok so after having this code,

``````for key in my_dictionary:
max_value = my_dictionary[key]
max_key = key
break
for thing in my_dictionary:
if my_dictionary[thing] > max_value:
max_value = my_dictionary[thing]
if my_dictionary[thing] == max_value:
return thing
``````

Now, I’m stuck. How would you use `max_key` in this for loop?

Let’s use `key` instead of thing. The key is only the label. The value is the thing (object)

``````max_value = my_dictionary[key]
max_key = key``````
``````for key in my_dictionary:
max_value = my_dictionary[key]
max_key = key
break
for key in my_dictionary:
if my_dictionary[key] > max_value:
max_value = my_dictionary[key]
if my_dictionary[key] == max_value:
return max_key
``````

Since we don’t know that our initial value was the actual maximum, can we make this inference?

Maybe, but why would we?

``````if my_dictionary[thing] > max_value:
max_value = my_dictionary[thing]
``````

This code would only run if there is a value greater than `max_value`. If not, it would return `thing`.

But since we don’t know the maximum is it feasible we can return before completely iterating the dictionary?

Wait, I’m kind of lost. In the above for loop, we have a set `max_value` and a set `max_key`. In the lower for loop, we iterate through the keys of my_dictionary and check if the current key’s value is greater than `max_value`. If it is, then we would set `max_value` equal to that key’s value. Then under that, we check if the current key’s value is equal to `max_value` and if it is return `max_key`.

Wait, my code returns the current key if it’s value is equal to max_value, which means that it would stop iterating at a certain point, and that’s not what we want right? We want it to iterate through the entire dictionary.

Right. We need to iterate the entire dictionary and keep a copy of both max_value and max_key as we go.

So maybe I could do something like this:

``````for key in my_dictionary:
if my_dictionary[key] > max_value:
max_value = my_dictionary[key]
max_key = key
``````

Let that finish iterating all the way, then make another loop.

``````for key in my_dictionary:
if my_dictionary[key] == max_value:
return max_key
``````

So now at least it’s iterating through the entire dict. to get `max_value` so I can compare them in this next loop?

No loop needed after that. Just return the max_key. This assumes we have initialized `max_value` and `max_key` before the loop. Recall that when we set the initial value we didn’t actually iterate, but took the first key/value and used that as a starting value for comparison.

Ok nice. So final code would look like this:

``````def max_key(my_dictionary):
for key in my_dictionary:
max_value = my_dictionary[key]
max_key = key
break
for key in my_dictionary:
if my_dictionary[key] > max_value:
max_value = my_dictionary[key]
max_key = key
return max_key
``````
1 Like

I’m not sure if you could really call it collaborating, but it was nice figuring out an alternate solution with you!

1 Like

Right on! It may look clunky but it works with a minimum of code patterns, and does not use any built-ins. This model of code may seldom be used in production but it is infinitely important in developing our thinking. Well done.

1 Like

Hi Everyone, I would like to share with you the way that I chose to solve it. (I saw a lot of methods to solve it until I finished my own, you rock guys )

``````def max_key(my_dictionary):
max = 0
for key in my_dictionary.keys():
if my_dictionary[key] > max:
max = my_dictionary[key]
output = key
return output
# Uncomment these function calls to test your  function:
print(max_key({1:100, 2:1, 3:4, 4:10}))
#print 1
print(max_key({"a":100, "b":10, "c":1000}))
#"c"
``````
1 Like

A sort of compilation of different approaches:

``````def max_key(my_dictionary):
maxK, maxV = list(my_dictionary.items())[0]
for k in my_dictionary:
if my_dictionary[k] > maxV:
maxV = my_dictionary[k]
maxK = k
return maxK

# for time efficiency, check https://stackoverflow.com/a/14624923
def max_key2(my_dictionary):
return list(my_dictionary.keys())[list(my_dictionary.values()).index(max(my_dictionary.values()))]

def max_key3(my_dictionary):
for k in my_dictionary:
if my_dictionary[k] == max(my_dictionary.values()):
return k

def max_key4(my_dictionary):
return max(my_dictionary, key=my_dictionary.get)
``````

How could we compare the efficiency of each approach against a large dataset?

I saw something called `profile.run()` mentioned in this post from Stack Overflow, but could not really figure out the docs with my current knowledge/vocab nor could I implement it on my terminal…

This is not my area but it never hurts to examine things and see what we spot. The first and last are both linear with a constant of 2 (for the two iterations) so O(2N). The second one looks to have a constant of 4 given there are four iterations, but still linear.

The third one would be the least efficient owing that it is quadratic (nested iteration). It could be cured by caching the max() before the loop. It never changes. Then it would be linear with a constant of 2.

Owing that we could very likely conclude that the source code for `max()` is highly optimized. The fourth one would be a best bet and it’s doubtful we as learners or even seasoned programmers will ever top that for this language. I suspect the source code is written in some flavor or C.

The thing I like about the first example is it is closest to a naive implementation It still uses built-ins, though. `list()` and `dict.items()`. The fully naive form will use only linear iteration.

``````>>> def max_key(d):
k, v = (None, float("-inf"))
for h in d:
if d[h] > v:
k, v = (h, d[h])
return k

>>> max_key({"a":100, "b":10, "c":1000})
'c'
>>>
``````

The only difference is that it uses negative infinity as the minimum instead of a value from the dictionary.

``````def max_key(my_dictionary):
for key, value in my_dictionary.items():
if value == max(my_dictionary.values()):
return key
``````

Not sure if it could fulfil all the conditions.

Here was my solution

``````def max_key(my_dictionary):
i = -9999999
for value in my_dictionary.values():
if value > i:
i = value
for key, value in my_dictionary.items():
if value == i:
return key
``````

Really cool to see some of these more concise answers! I’m impressed.
Also - if anyone knows a shorter hand way to get a really low integer than literally typing out `-9999999`, let me know!

If you check through some of the previous answers you’ll find some neat ways of achieving your goal. Perhaps a small integer isn’t what you really need though, you’re just interested in finding the maximum form a set of values, why not start with one of them?