pythonpython-2.7python-3.xordereddictionary

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


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!


Solution

  • 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 write a sort function that you can apply when the order is actually important.