Dictionary-maximum value

If a have a dictionary with keys and the value for each key, for example:
Anne=3, Mark=5, Eve=2
How can I create a loop that gives the key with the highest value and then print both of them (the key, and the value, in the example above it would be Mark 5)?
Thank you in advance

You can do it with an explicit loop and keeping track of the max value and the key for that value. It’s easy to understand, but verbose.

(I’ve modified your dictionary because the max value (5) was also associated with the max key (Mark). So some incorrect algorithms would return the same answer. By making one of the keys alphabetically later, this particular problem is more obvious)

d = dict(Xena=3, Mark=5, Eve=2)
max_value = 0
max_key = None
for key, value in d.items():
    if value > max_value:
        max_value = value
        max_key = key
print(f"Max value is {max_value} associated with {max_key}")

But a simpler way is to pass all the dictionary items to max and tell it what part of the item it should use for sorting.

d = dict(Xena=3, Mark=5, Eve=2)
print(max(d.items(), key=lambda t: t[1]))

# or for folks that prefer to not use lambdas:
from operator import itemgetter
print(max(d.items(), key=itemgetter(1)))

Hi Izan,

Start by writing a loop to inspect the keys and values of the dict. Do
you need help writing a loop?

Then, as you inspect each value, see if it is the highest value or not.

You can do that by recording the highest value seen, and its key, and
updating them as you go. So you have something like:

Pick a first value for the highest value
highest_value = ...  # something goes here

then as you iterate over the dict items, you do:

if value > highest_value:
    highest_value = value
    matching_key = key

Do that for each key and value.

The tricky part is getting an initial value for the highest value. It
needs to be an actual value from the dict, but it is actually quite
tricky to get one on its own. Here’s a trick:

for highest_value in mydict.values():

will give you an arbitrary value as the initial guess for the highest
value, and then you can loop over all the keys and values.

Does that help?

Hey BowlOfRed,

Be careful about doing students’ homework for them by giving them a
complete (or almost complete) solution.

Also, you should consider what happens if the values in the dict are all
less than zero:

dict(Alice=-3, Bob=-2, Carol=-1, Eve=-7, Xena=-9)

Your function will silently do the wrong thing.