Keeping a dictionary (or similar structure) ordered in Python

Question:

I need to work with two data structures that inherit all the properties of dictionaries in Python3.8. But I want these dictionaries to be ordered with respect to the key every time I insert an element. One dictionary has to keep an ascending order while the other a descending order.

For example, consider the two dictionaries

dic1 = {1:'a',2:'b',3:'c',5:'e'} #This dictionary needs to keep the order of ascending keys
dic2 = {5:'e', 3:'c',2:'b',1:'a'} #This dictionary needs to keep the order of ascending keys

and let’s add an element to both of them

dic1[4]='d'
dic2[4]='d'

After these operations, I want the two dictionaries to be

> dic1 == {1:'a',2:'b',3:'c',4:'d',5:'e'} #This dictionary needs to keep the order of ascending keys
> True
> dic2 == {5:'e', 4:'d', 3:'c',2:'b',1:'a'} #This dictionary needs to keep the order of ascending keys
> True

without having to sort the dictionaries through dict(sorted(dic1)) or dict(sorted(dic2,reverse=True)).

I know that I can define dic1to be a SortedDictfrom sortedcontainers. However, in the documentation of sortedcontainers.SortedDictI cannot find how to define the order of the keys (ascending or descending).

Any insight?

Asked By: apt45

||

Answers:

The documentation has exactly the example of what you’re trying to do:

>>> sd = SortedDict(neg, enumerate('abc', start=1))
>>> sd
SortedDict(<built-in function neg>, {3: 'c', 2: 'b', 1: 'a'})

>>> keys = sd.keys()
>>> list(keys)
[3, 2, 1]
Answered By: gimix