Why sum,min,max,sorted operate on keys in python dictionary?

Why sum,min,max,sorted operate on keys in python dictionary?

They are always only useful if operated on values.
An example case is dictionary with frequencies, like element: frequency.

Yeah at times dictionary are meant to have different types of value each, but in those situations operation on keys are not useful either if it can’t be on values.

I am asking about a feature request to implement these dictionary functions on values instead.

Only then it will be analogous to list as well, where we operate not on indexes but on values.

Those functions work on iterables. The default iteration for dictionaries is by key. Changing the behavior of sum, min, max, and sorted would require these functions to treat dictionaries as a special case and break existing code. That’s hardly worth it when it’s trivial to write sum(d.values()), min(d.values()), etc.

2 Likes

What evidence do you have to support this claim?

2 Likes

There are often times where we want to sort on keys. There are times when we want to sort on the pairs. There are times when we want to sort on the values. We can do whichever we choose.

>>> d = {n: str(n) for n in range(1, 10)}
>>> d
{1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
>>> sorted(d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sorted(d.values())
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> sorted(d.items())
[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9')]
>>> {k: v for k, v in sorted(d.items(), key=lambda x: x[1])}
{1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
>>> {k: v for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True)}
{9: '9', 8: '8', 7: '7', 6: '6', 5: '5', 4: '4', 3: '3', 2: '2', 1: '1'}

The default is in the keys because that is what we iterate over by default.

1 Like

What sort of thing is considered evidence? an example ? I suppose this isn’t court.

You wrote “They are always only useful if operated on values.”.

That’s not true.

Sometimes you want to sort by key, other times by value, sometimes by one and then the other. For example, if you’re counting words, you might want to list the counts alphabetically, or from highest to lowest count and alphabetically where words have the same count.

2 Likes