Python program to get key with maximum value in Dictionary

In this article, we will learn how to get key with maximum value in Dictionary in Python. Dictionary is used to store the data value in key: value pair. A dictionary is a mutable, unordered collection that does not allow any duplicates.

Examples

Input: {'Python': 1000, 'C++': 150, 'C': 290, 'Java':370, 'PHP': 1050, 'HTML': 250}
Output: PHP

Input: {'Space': 280, 'Time': 200}
Output: Space

Key with maximum value in Dictionary using Python

Method 1

Use the max() function to find the maximum value. Use get function to extract the key of maximum value.

names = {'Shopie': 300, 'Ram': 120, 'kayalan': 450, 'Hope': 320}

maxKey = max(names, key=names.get)
print("Key with maximum value is ", maxKey)

Output

Key with maximum value is kayalan

Method 2

Use itemgetter() function to get the item that has the maximum value.

import operator

rivers = {'krishna': 200, 'Ganga': 350, 'Yammuna': 120}

maxKey = max(rivers.items(), key = operator.itemgetter(1))[0]
print(maxKey)

Output

Ganga

Method 3

lambda is an anonymous function that can take many arguments but only one expression. Use lambda and max() to get the key with maximum value.

places = {'Asia': 13904, 'USA': 123401, 'Japan': 3782, 'China': 123455}

maxKey = max(places, key = lambda x: places[x])
print(maxKey)

Output

China

Method 4

Firstly, create two separate list value, key to store the values and keys of the dictionary.

Now find the maximum value in the value list using the max() function. Use the index() function to get the index of maximum value. Finally print the key[index_value]

places = {'Asia': 13904, 'USA': 123401, 'Japan': 3782, 'China': 123455}

value = list(places.values())
key = list(places.keys())
print(key[value.index(max(value))])

Output

China

Also, read

Leave a Reply

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