The key argument tells the max function which max should be used. Default it will use the values of the elements itself.

dataset = [1, 1, 2, 2, 3, 4, 5, 6, 2, 1, 9, 2, 3, 2, 2, 2]
max(dataset) # 9, since 9 is the max value in this dataset
max(dataset, key=dataset.count) # 2 since 2 occurs the most in this dataset

# You can also use this:
sorted(dataset, key=dataset.count)
# [4, 5, 6, 9, 3, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]

In the last example all elements are sorted from low to high based on the count (how often is the value in the dataset).

Answer from 3dSpatialUser on Stack Overflow
Top answer
1 of 8
420

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'
2 of 8
25

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4
Discussions

python - Get max key in dictionary - Stack Overflow
I have a dictionary that looks like this MyCount= {u'10': 1, u'1': 2, u'3': 2, u'2': 2, u'5': 2, u'4': 2, u'7': 2, u'6': 2, u'9': 2, u'8': 2} I need highest key which is 10 but i if try max(MyCoun... More on stackoverflow.com
🌐 stackoverflow.com
Get the max count of values and return the key in a dictionary
Zan Le is having issues with: Hi, could you please help with my function most_courses() please. I am not sure why it does not pass More on teamtreehouse.com
🌐 teamtreehouse.com
2
August 22, 2017
python - Usage of key in max function and argument-less count method - Stack Overflow
It's just that instead of passing ... to key, the list_x.count function itself was passed. set() is being used here because a set can only contain unique elements. Since you are getting the count for each element, it is faster to use a set so you are not calling list_x.count('B') multiple times. ... Sign up to request clarification or add additional context in comments. ... This computes the element in list_x that is repeated the most. set(list_x) is used to compute the max over, and ... More on stackoverflow.com
🌐 stackoverflow.com
python - Getting key with maximum value in dictionary? - Stack Overflow
I have a dictionary where keys are strings, and values are integers. stats = {'a': 1, 'b': 3000, 'c': 0} How do I get the key with the maximum value? In this case, it is 'b'. Is there a nicer app... More on stackoverflow.com
🌐 stackoverflow.com
🌐
All About AI-ML
indhumathychelliah.com › 2020 › 08 › 17 › how-to-use-key-function-in-max-and-min-in-python
How to Use Key Function in Max() and Min() in Python – All About AI-ML
January 2, 2022 - Refer to my story for how to use the key function in the sorted() function. Return the largest item in an iterable or the largest of two or more arguments. If one item is given, it should be iterable. The largest item in the iterable is returned. max(iterable, *[, key, default])
🌐
Robjwells
robjwells.com › 2015 › 08 › python-counter-gotcha-with-max
Primary Unit – Python Counter gotcha with max
What? Here’s the gotcha: Python counters are a dictionary subclass. Call max with a dictionary and it’ll get the greatest key, because keys are what you get when you iterate over a dictionary.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-keys-with-maximum-value
Keys with Maximum Value - Python - GeeksforGeeks
November 18, 2025 - This method manually loops through all keys, compares each value with the maximum value, and stores the keys that match.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get Maximum/Minimum Values and Keys in Python Dictionaries | note.nkmk.me
May 14, 2023 - Iterate dictionary (key and value) with for loop in Python · By passing this to the max() and min functions, you can retrieve the maximum and minimum values of the dictionary.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - Python
Explanation: max() function is used to find the maximum element where key=d.get ensures the comparison is made based on the values (not keys).
Published: July 11, 2025
🌐
Medium
medium.com › analytics-vidhya › how-to-use-key-function-in-max-and-min-in-python-1fdbd661c59c
How to Use Key Function in Max() and Min() in Python | by Indhumathy Chelliah | Analytics Vidhya | Medium
January 17, 2024 - Refer to my story for how to use the key function in the sorted() function. Return the largest item in an iterable or the largest of two or more arguments. If one item is given, it should be iterable. The largest item in the iterable is returned. max(iterable, *[, key, default])
🌐
Reddit
reddit.com › r/learnpython › why does max(set(l), key=l.count) generate the mode of a list?
r/learnpython on Reddit: Why does max(set(l), key=l.count) generate the mode of a list?
March 1, 2017 -

Given a list of number, l, can someone explain in detail why max(set(l), key=l.count) compute the mode (most frequently occurring number)? I've seen "key=" in several places and I still don't understand the meaning of it. Also why are we converting the list "l" to a set? Thanks in davance!

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-maximum-record-value-key-in-dictionary
Python - Maximum record value key in dictionary - GeeksforGeeks
May 14, 2023 - In this, we perform the task of iteration using max key argument, passing a lambda function that binds the required logic. ... # Python3 code to demonstrate working of # Maximum record value key in dictionary # Using max() + lambda function # initializing dictionary test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10}, 'is' : {'Manjeet' : 8, 'Himani' : 9}, 'best' : {'Manjeet' : 10, 'Himani' : 15}} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing search key key = 'Himani' # Maximum record value key in dictionary # Using max() + lambda function res = max(test_dict, key = lambda sub: test_dict[sub][key]) # printing result print("The required key is : " + str(res))
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
The function returns the values of dictionaries. Based on the values (rather than the dictionary's keys), the key having the maximum value is returned.
🌐
GeeksforGeeks
geeksforgeeks.org › python-get-key-with-maximum-value-in-dictionary
Get key with maximum value in Dictionary - GeeksforGeeks
Sometimes, while working with python dictionary, we can have problem in which each key in itself is a record with several keys and we desire to substitute the value as maximum value of keys of dictionary. This kind of problem can have application in many domains that involves data.
Published: May 6, 2025
🌐
datagy
datagy.io › home › python posts › python: get dictionary key with the max value (4 ways)
Python: Get Dictionary Key with the Max Value (4 Ways) • datagy
February 23, 2022 - The Quick Answer: Use the max() function to get the dictionary key with the max values ... Dictionaries in Python are one of the main, built-in data structures. They are collections of items, each consisting of a key:value pairs.
🌐
Python.org
discuss.python.org › ideas
Allow `min()` and `max()` to return both the key and value - Ideas - Discussions on Python.org
September 5, 2024 - Problem Currently, min() and max() return only the minimum/maximum value, or in cases where the input is a mapping (like a dictionary), only the key. There are many situations where both the value and the associated key or object are needed. This leads to redundant code where users have to ...