
On Sat, May 29, 2021 at 06:54:15PM +0200, Marco Sulla wrote:
Since `dict` now is ordered, how about a `sort()` method? It could have the same signature of list.sort(), with an optional parameter "by" that can be "keys" or "values" ("keys" could be the default).
Dicts keep their insertion order stable, that doesn't mean that they are sortable. They aren't lists where you can just reorder items, the implementation is more complex than a simple list of (key,value) pairs that can be sorted. My understanding of the implementation is that the only practical way to sort a dict is to sort the items ahead of time and then build it. I don't know the current implementation, but I think it *might* be something like Raymond Hettinger's proposal for a compact, order-preserving, key-sharing dict: https://mail.python.org/pipermail/python-dev/2012-December/123028.html If you can think of a way to sort something like that, without changing the way hash lookups work, and more efficiently than just sorting the items and building a new dict, remember that the implementation can change at any time. The bottom line here is that *dicts aren't lists* and it doesn't make sense to sort them. If you want a sortable data structure, stick to a list or a tree, or a specialised data structure designed for the task. -- Steve