All examples I could find (in the documentation, etc.) define OrderedDicts by passing 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, it is possible to initialize an OrderedDict by providing no parameters to the constructor, which leads it to preserve the order in which key,value pairs are added.
I am looking for a kind of construct that resembles the following, except without "d.items()". Essentially, I'm asking it to remember a mechanism without providing it an example, which might sound crazy. Is my only option to "hack" this by providing an initial "d" (below) with a single item, or is there a better way?
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
Thank you!
OrderedDict
only has one sorting algorithm: insertion order. Whatever order the items are added to the OrderedDict
is the order the OrderedDict
has.
If you want some other method you can either write your dict
subclass or just a sort function that you can apply when the order is actually important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With