In this article we will discuss ways to find the maximum value in dictionary and also the all keys with the maximum value.

Find a key with maximum value in Dictionary

Suppose we have a dictionary of string and int i.e.

Now suppose we want to find the maximum value in the dictionary and also the key associated with it.

For that we are going to use max() function i.e.

Output:

How did it worked ?

To know how it worked we need to explain little bit about max() function i.e.

Arguments:

  • iterable : An Iterable object
  • key : A function that will be applied to each item in the iterable and it returns a value based on the passed argument.

Returns:

  • It returns the item with maximum value in the Iterable. If key function is not provided then it directly compare the items in Iterable to find out the maximum value. If key function is provided then instead of comparing items directly it will call the key function on item and then compare it with others.

Now in the above example to find the key with max value in dictionary. We passed the Iterable returns by dict.items(), that is basically an Iterable of key / value tuples. Now max() function can’t compare these tuples directly. So, we passed a key function too i.e.

This key function accepts a tuple as an argument and returns the 2nd value in tuple i.e. item at index 1. So, basically when a tuple of key, value is passed to this function, it returns the value field from that tuple.

So in the following code,

sampleDict.items() returns an Iterable and the max() function calls the key function on each item of this Iterable before comparing it with other items in the iterable. So, basically max() function will compare items like,

It return the item (key/value tuple) with maximum value in dictionary. From it we fetched the key and value fields.

If there are multiple keys in the dictionary with maximum value then this solution will not work, because max() function always returns the first occurrence of maximum value. So, what if we want to find all the keys with maximum value ?

Find all keys with maximum value in Dictionary

Suppose we have a dictionary in which multiple keys have maximum value i.e.

Now to find all the keys with maximum value, we will first use max() function to find the first key with max value like above. Then once we know the max value in dictionary then we will iterate over all the items in dictionary to find out all the keys with max value i.e.

Output:

Complete example is as follows:

Output:

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.