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

Why not use a for loop?

This would allow multiple key value pairs to be given in the case that there are multiple values that are equally the lowest.

Suppose that we take your dictionary, but we add another key value pair to it that is tied for the minimum.

So instead of just

We also add ‘e’ : 1

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

Simply using min() will only select the first key it encounters, d, which can be misleading because it technically isn’t the lowest, there is also e which is tied for the lowest.

If instead you loop through the keys and values, and check if the value is equal to the min() of data.values(), then we can get both d and e which may be considered more accurate.

data = {'a': 5, 'b': 2, 'c': 7, 'd': 1, 'e' : 1}
for key, value in data.items():
    if value == min(data.values()):
        print(key, value)

That seems like a separate issue, you could also want all minima without keys involved.

(Btw I think it’s a bad idea to show quadratic runtime code when linear time is easy.)

2 Likes

Very nice. Surprised that the most bytecode-laden approach turns out to be the fastest by avoiding repeated function calls and scanning the dict only once.