If I need to sort OrderedDict
I used to use such statement that works fine:
from collections import OrderedDict
# defining a dictionary
od = OrderedDict({'a': 5, 'b': 10, 'c': 7})
# ... some changes like adding new keys, removing old keys, etc.
# sorting the dictionary
od_sorted = OrderedDict(sorted(od.items(), key=lambda e: e[1]))
But it has a disadvantage: I create a new OrderedDict instance and list instance (by sorted
) that can be expensive regarding memory usage in case if the original dictionary is big. Is there a way to perform sorting inside the original dictionary without creading a new instance or additional objects? I expected to find something like od.sort(key=lambda ...)
, but found nothing similar:
>>> dir(od)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'move_to_end', 'pop', 'popitem', 'setdefault', 'update', 'values']
I saw the question How to sort OrderedDict of OrderedDict?, of course. It's said nothing about the efficiency of suggested approaches.