Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 429
aralar Avatar asked Sep 29 '22 10:09

aralar


1 Answers

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.

like image 184
Ethan Furman Avatar answered Oct 21 '22 05:10

Ethan Furman