A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-keys-with-maximum-value/ below:

Keys with Maximum value - Python

Keys with Maximum value - Python

Last Updated : 24 Feb, 2025

In Python, dictionaries are used to store data in key-value pairs and our task is to find the key or keys that have the highest value in a dictionary. For example, in a dictionary that stores the scores of students, you might want to know which student has the highest score. Different methods to identify the key or keys associated with the maximum value are:

Using max() + list comprehension + values()

This approach is a simple and most efficient way to find the key or keys with the highest value in a dictionary. First, we use the max() function to find the highest value in the dictionary. Then, with list comprehension, we can loop through the dictionary and collect all the keys that have this maximum value. The values() method helps to easily get all the values from the dictionary, which we use to find the maximum.

Python
d = {'Gfg' : 2, 'for' : 1, 'CS' : 2}
temp = max(d.values())
res = [key for key in d if d[key] == temp]
print(res)

Explanation:

Using all() + list comprehension

In this approach, we use list comprehension to loop through the dictionary and check if the value of each key is equal to the maximum value. The all() function is used to verify if all the conditions are met for each key-value pair.

Python
d = {'Gfg' : 2, 'for' : 1, 'CS' : 2}
res = [key for key in d if all(d[temp] <= d[key] for temp in d)]
print(res)

Explanation:

Using for loop

In this approach, we manually loop through the dictionary and check the value of each key. If the value matches the maximum value, we add the key to a list.

Python
d = {'CS': 2, 'Gfg': 2, 'for': 1}
max_val = max(d.values())
max_keys = []

for key in d:
    if d[key] == max_val:
        max_keys.append(key)

print(max_keys)

Explanation:

Using filter() and lambda()

In this approach, we use the filter() function combined with a lambda() function to filter out the keys that have the maximum value. The filter() function checks each key-value pair, and the lambda() function defines the condition (whether the value is equal to the maximum value).

Python
d = {'Gfg': 2, 'for': 1, 'CS': 2}
max_val = max(d.values())
res = list(filter(lambda x: d[x] == max_val, d))

print(res)

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4