Allow `min()` and `max()` to return both the key and value

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 call the function twice or perform extra lookups.

data = {'a': 5, 'b': 2, 'c': 7, 'd': 1}

# Current behavior
min_key = min(data, key=data.get)  # 'd'
min_value = data[min_key]  # 1

Solution

Introduce a return_both keyword argument to min() and max(). When set to True, the function returns a tuple containing both the key (or element) and the value used for comparison.

# Proposed behavior with return_both=True
min_key, min_value = min(data, key=data.get, return_both=True)  # ('d', 1)

Benefits

  • Simplifies code when both the element and the comparison value are needed.
  • Reduces the need for extra lookups or redundant calls to min() and max().
  • Potentially increases performance due to an eliminated dict lookup.

Backward Compatibility

The default behavior remains unchanged. Only when return_both=True is explicitly set will a tuple be returned.

I’m open to suggestions for naming for the return_both keyword argument.

>>> data = {'a': 5, 'b': 2, 'c': 7, 'd': 1}
>>> list(data)
['a', 'b', 'c', 'd']
>>> min(data)
'a'
>>> key, value = min(data.items(), key=lambda x: x[0])
>>> key
'a'
>>> value
5

min returns the minimum of an iterable. by default a dictionary will iterate over it’s keys, and thats why it picks the min of the keys, not values. if you want to return something else, pass in a different iterable like dict.items(), and then use the flexible key argument.

2 Likes

See Add `index: bool` keyword to `min`, `max`, `sorted`

3 Likes
>>> data = {'a': 5, 'b': 2, 'c': 7, 'd': 1}
>>> min(data.items())
('a', 5)

If you use min or max on the items() of a dictionary you get the key value pair.
You can also use the key parameter in min or max to compare the values as opposed to the keys:

>>> min(data.items(), key=lambda x: x[1])
('d', 1)

This functionality exists already although you do have to know how to do it.

4 Likes

Thanks everyone! I was thought I couldn’t be the first person with the problem, considering how general it’s. Sorry for the noise.

Thanks for the replies, it’s appreciated!

Edit: Maybe this snippet with a short explanation can be added somewhere in the docstring? What would be a fitting place, if any (considering it’s generalizable to min, max, sorted, and probably more)?

min(data.items(), key=lambda x: x[1])