How to find the max value in a dictionary in python?

Dictionary is an unordered collection of items stored in the form of key-value pairs. It is widely used in almost all programming languages to store data with a specific key and its corresponding value. The best-case scenario for a Dictionary object is when you have a lot of information that can be stored efficiently as key-value pairs (a lot of discrete values that are naturally integer indexes or other similarly small integers). However, sometimes it becomes challenging to find the maximum value in a dictionary. In this blog, we will learn how to find the max value in a dictionary in python.

First of all, lets have a brief introduction about dictionaries. If you have good understanding of dictionaries then you can skip the introduction part.

How dictIONARIES ARE CREATED?

Dictionaries are created using a curly bracket {} consisting of key-value pairs separated using commas. Python provides an inbuilt-function formkeys() which returns a dictionary as output having a specific key and values.

#the fromkeys() method returns a dictionary with the specified keys and the specified value
x={'key1', 'key2', 'key3'}
y= 5
dict_01 = dict.fromkeys(x)
print(dict_01)

dict_02 = dict.fromkeys(x,y)
print(dict_02)
{'key1': None, 'key3': None, 'key2': None}
{'key1': 5, 'key3': 5, 'key2': 5}

In this article, we’ll cover the following topics in detail:

  • Find the maximum value in the dictionary
  • Find the key with maximum value in the dictionary
  • Find maximum value in a dictionary of lists
  • Find maximum value in a dictionary consisting of dictionaries stored as values

Find the maximum value in the dictionary

Method 1: using Max () function

The maximum function max() returns the maximum value. In the dictionaries, when max() function is applied on the dictionary, it returns the largest key. As in the example below, key3 is the largest key.

df = {'key1' : 5, 'key2': 35, 'key3': 25}

max_value = max(df)

print(max_value)
key3

In case of values, the max() function returns the highest value in the dictionary.

df = {'key1' : 5, 'key2': 35, 'key3': 25}

max_value = max(df.values())

print(max_value)
//Output
35

Find the KEY WITH maximum value in the dictionary

Method 1: using Get() Method

The get() method returns the item’s value with the specified key.

#The get() method returns the value of the item with the specified key
car = {
    "brand": "xyz",
    "model": "abc",
    "year": 1964
}

x = car.get("year")
print(x)
1964

We can use get() method along with max() function to get the key with maximum value. It provides the key with the highest value as shown in the code below.

df = {'key1' : 5, 'key2': 35, 'key3': 25}

max_value = max(df, key=df.get)

print("Maximum value = ",max_value)
Maximum value =  key2

Method 2: Using Lambda Function

The Lambda function is an anonymous function which is almost similar to the regular function. We can use a combination of max() and lambda function to find the key having maximum value.

df = {'key1' : 5, 'key2': 35, 'key3': 25}

max_value = max(df, key=lambda x:df[x])

print("Maximum value is of ",max_value)
Maximum value is of key2

In order to check whether the results are correct or not, print the value of that key as shown in the code below.

df=df.get("key3")

print('key3 = ',df)
key3 =  25

Now, you know how to find the maximum value in a dictionary or a key with maximum value.

METHOD 3: USING VALUE() AND KEY() Functions

First of all, access the keys and values of a dictionary in a separate lists and then apply max() function to find the maximum value. The following code demonstrates how to use values() and key() functions in combination with the max() function to find the key consisting of maximum value.

df = {
      'a':29,
      'b': 15,
      'c':54,
      'd':20
      }

max_value = list(df.values())
max_key= list(df.keys())
print(max_key[max_value.index(max(max_value))])
c

Find maximum value in a dictionary of lists

Uptil now, we have discussed a simple dictionary consisting of a single value in each key. Now, these values are not always a single numeric value or a string. The dictionary can also consists of lists stored against different keys.

Now the task is to find maximum value in a dictionary consisting of lists stored as values against keys. Suppose you have a dictionary consisting of a list of fruits and their prices. You have to find the maximum price. In this case, you know that you know the key name i.e., ‘prices’.

df = {'student':['apple','mango','banana','apricot','orange'],
      'prices':[20,15,25,15,30]}

max_value = max(df['prices'])

print("The highest price is ",max_value)

The highest price is  30

If you have to find the maximum value in the whole dictionary then you need to traverse through all keys and check all the values stored in that key to find the maximum value.

df = {
            'a': [12,65,3,56,32,42],
            'b': [20,15,25,95,30]
         }

max_value = max(max(df[key] for key in df))

print("The maximum value is ",max_value)

The maximum value is  95

Find maximum value in a dictionary consisting of dictionarIES storeD as values

To find the maximum value from the nested dictionary, we will use reduce function along with the aggregate process. Reduce function only returns one value or one argument.

In the below example, the reduce function returns the key with a maximum value.

from functools import reduce

d = {'k1' :{'tricky': 10, 'target': 20}, 'k2': {'person': 30, 'fee': 40}}

maxvalue = reduce(lambda x,y:max(x,y), d)

print(maxvalue)
'k2'

Summing all up, we have covered how to access the maximum value in a dictionary in python. However, in some cases, it’s a challenging task, but after all methods, you may be able to acquaint the maximum value in the dictionary.

Leave a Comment

Your email address will not be published. Required fields are marked *