Add a dict.sort() method

Python dictionaries are now ordered but there’s no way to reorder a dictionary in place, you have to create a new one:

from operator import itemgetter
my_dict = {2: "a", 1: "b"}
my_dict = dict(sorted(my_dict.items(), key=itemgetter(0)))

It would be nice if they could be reordered in place like lists, with the same interface.

The argument passed to the function passed in as the key= parameter to dict.sort() would be the key, since that’s how sorted(my_dict, key=some_func) behaves and in general that’s what you get when you treat a dict as an iterable. To sort by values you would do

my_dict.sort(key=my_dict.get)

Python dictionaries are now ordered but there’s no way to reorder a
dictionary in place, you have to create a new one:

from operator import itemgetter
my_dict = {2: "a", 1: "b"}
my_dict = dict(sorted(my_dict.items(), key=itemgetter(0)))

It would be nice if they could be reordered in place like lists, with the same interface.

That seems overly elaborate. What’s wrong with this?

my_dict = dict(sorted(my_dict.items()))

The argument passed to the function passed in as the key= parameter
to dict.sort() would be the key, since that’s how sorted(my_dict, key=some_func) behaves and in general that’s what you get when you
treat a dict as an iterable. To sort by values you would do

I’m curious,. When do you want to sort by other than the keys? Genuinely
curious, not saying this is in any way wrong - I’ve just never wanted to
do it myself.

Also, what’s the benefit of sorting a dict in place?

This seems simple enough to me enough to not warrant a special method on
dict.

Cheers,
Cameron Simpson cs@cskk.id.au

You’re right, nothing.

How do I sort a dictionary by value” is the 15th most upvoted question under the [python] tag on Stack Overflow.

The same as sorting a list in place: saving on memory and having dict have a similar interface to list, since both are ordered it seems like an arbitrary limitation that one can be sorted in place and the other can’t.

There is a big difference between list and dict. List is implemented by array. During sort, the list is accessible from the key function or __cmp__ method although the order during sort is implementation detail.

On the other hand, dict is implemented by hash table and array. key function or __cmp__ may access the dict during sort. So dict.sort() needs to keep hash table consistent with array during sort. It is difficult and sort performance may be horrible.

dict(sorted(my_dict.items())) will be much faster and safe compared to inplace dict sort.

2 Likes

If something must be added, maybe it would make sense to do something like OrderedDict.sorted_by_key() instead that basically does the same as the sorted() one-liner.