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 list
s, 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)