Is it possible to initialize an empty OrderedDict in Python using a predefined sorting mechanism?

All the examples that I could find ( in the documentation , etc.) define OrderedDicts, passing the data to the constructor. From the docs:

# regular unsorted dictionary d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) 

On the other hand, you can initialize an OrderedDict without providing any parameters to the constructors, which preserves the order in which key pairs and values ​​are added.

I am looking for some kind of construct that looks like the following, except without "d.items ()". In fact, I ask him to remember the mechanism without giving him an example that might seem crazy. Is my only option to β€œhack” this by providing the original β€œd” (below) with one element, or is there a better way?

 OrderedDict(sorted(d.items(), key=lambda t: t[0])) 

Thanks!

+5
source share
1 answer

OrderedDict has only one sorting algorithm: insertion order. No matter what elements are added to the OrderedDict , this is the order of the OrderedDict .

If you want to use some other method, you can either write your dict subclass, or just a sort function that you can apply when order is really important.

+1
source

Source: https://habr.com/ru/post/1206842/


All Articles