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.

# Create a dictionary of string and int
sampleDict = {  'Ritika': 5, 'Sam': 27, 'John' : 10 , 'Sachin' : 14, 'Mark' : 19 }

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.

# Find Key with Max Value
itemMaxValue = max(sampleDict.items(), key=lambda x : x[1])

print('Max value in Dict: ', itemMaxValue[1])
print('Key With Max value in Dict: ', itemMaxValue[0])

Output:
Max value in Dict:  27
Key With Max value in Dict:  Sam

How did it worked ?

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

max(iterable, *[, key, default])

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.

key=lambda x : x[1]

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,

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

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,
key(item1) < key(item2)

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.

# Create a dictionary of string and int
sampleDict = {'Ritika': 5, 'Sam': 27, 'John': 12, 'Sachin': 14, 'Mark': 19, 'Shaun' : 27}

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.
# Find item with Max Value in Dictionary
itemMaxValue = max(sampleDict.items(), key=lambda x: x[1])

print('Maximum Value in Dictionary : ', itemMaxValue[1])

listOfKeys = list()
# Iterate over all the items in dictionary to find keys with max value
for key, value in sampleDict.items():
    if value == itemMaxValue[1]:
        listOfKeys.append(key)

print('Keys with maximum Value in Dictionary : ', listOfKeys)

Output:
Maximum Value in Dictionary :  27
Keys with maximum Value in Dictionary :  ['Sam', 'Shaun']

Python Dictionary Tutorial - Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows:

def main():


    print('*** Get key with max value in Dictionary ***')

    # Create a dictionary of string and int
    sampleDict = {  'Ritika': 5, 'Sam': 27, 'John' : 10 , 'Sachin' : 14, 'Mark' : 19 }

    print('Dictionary Contents : ', sampleDict)

    # Find Key with Max Value
    itemMaxValue = max(sampleDict.items(), key=lambda x : x[1])

    print('Max value in Dict: ', itemMaxValue[1])
    print('Key With Max value in Dict: ', itemMaxValue[0])


    print('*** Get All keys with max value in Dictionary ***')

    # Create a dictionary of string and int
    sampleDict = {'Ritika': 5, 'Sam': 27, 'John': 12, 'Sachin': 14, 'Mark': 19, 'Shaun' : 27}

    print('Dictionary Contents : ', sampleDict)

    # Find item with Max Value in Dictionary
    itemMaxValue = max(sampleDict.items(), key=lambda x: x[1])

    print('Maximum Value in Dictionary : ', itemMaxValue[1])

    listOfKeys = list()
    # Iterate over all the items in dictionary to find keys with max value
    for key, value in sampleDict.items():
        if value == itemMaxValue[1]:
            listOfKeys.append(key)

    print('Keys with maximum Value in Dictionary : ', listOfKeys)

if __name__ == '__main__':
  main()

Output:
*** Get key with max value in Dictionary ***
Dictionary Contents :  {'Ritika': 5, 'Sam': 27, 'John': 10, 'Sachin': 14, 'Mark': 19}
Max value in Dict:  27
Key With Max value in Dict:  Sam
*** Get All keys with max value in Dictionary ***
Dictionary Contents :  {'Ritika': 5, 'Sam': 27, 'John': 12, 'Sachin': 14, 'Mark': 19, 'Shaun': 27}
Maximum Value in Dictionary :  27
Keys with maximum Value in Dictionary :  ['Sam', 'Shaun']

Join a list of 2000+ Programmers for latest Tips & Tutorials