How to Find the Maximum Value in a Python Dict?

There are three problem variants of finding the maximum value in a Python dictionary:

  1. Find the maximum value and return this maximum value
  2. Find the maximum value and return a (key, value) tuple of both the key and the max value itself
  3. Find the maximum value and return only the key assigned to the max value

In the following, you’ll learn how to solve those in the most Pythonic way:

Find Maximum Value & Return Only Value

  • Get the dictionary values with d.values()
  • Return the maximum by passing those into the max() function
# mg Omega 3 per 100g
d = {
    "Salmon" : 2260,
    "Hering" : 1729,
    "Sardines" : 1480,
    "Flaxseeds" : 53400,
    "Eggs" : 400
}

max_val = max(d.values())

print(max_val)

The output is:

53400

Find Maximum Value & Return (Key, Value) Pair

  • Get an iterable of (key, value) pairs with dict.items()
  • Pass it into the max() function
  • Pass a key lambda function into max() returning the second tuple value to be the basis of comparison
# mg Omega 3 per 100g
d = {
    "Salmon" : 2260,
    "Hering" : 1729,
    "Sardines" : 1480,
    "Flaxseeds" : 53400,
    "Eggs" : 400
}

max_val = max(d.items(), key=lambda x: x[1])

print(max_val)

The output is:

('Flaxseeds', 53400)

Find Maximum Value & Return Only Key

  • Use the max() function
  • Pass the dictionary into it—per default, it finds the maximum key.
  • Set the optional key function to d.get that uses the value associated to the key as a basis for comparison.
# mg Omega 3 per 100g
d = {
    "Salmon" : 2260,
    "Hering" : 1729,
    "Sardines" : 1480,
    "Flaxseeds" : 53400,
    "Eggs" : 400
}

max_val = max(d, key=d.get)

print(max_val)

The output is:

Flaxseeds

Explanation

You can retrieve the maximal element of a dictionary using the max function. Recap, a dictionary stores (key, value) pairs. In our example, the keys are strings with the names of five different foods such as 'Eggs'. The dictionary maps each food name to a numerical value that describes the amount of healthy Omega 3 fats per 100g.

How to find the food (key) in the dictionary containing maximal Omega 3 (value)? To achieve this, we use Python’s built-in max function. But calling max(omega3_table) leads to a strange result. The default max function applied to a dictionary retrieves the maximal key. In the example, this would be the key ‘Sardines’ because it comes last in the alphabet.

To fix this, we specify the key parameter of the max function. The key parameter expects a function that assigns a value to each element in the sequence. This value is then used to determine the maximal value of the sequence. In our example, we use the dictionary value of the respective key by using the dict.get function. We assign the value omega3_table[x] to each sequence element x.

Conclusion

Eat one tablespoon of flaxseeds per day! They are among the healthiest foods on our planet.