Python Sorted Collections
Sorted Collections provides CPython-optimized mutable sorted collections (SortedList, SortedDict, SortedSet) that maintain their order automatically. As of version 2.1.0, it targets Python 3.7+ and is actively maintained, with releases typically following bug fixes or minor enhancements to ensure stability and performance.
Warnings
- breaking Direct access to internal, non-public attributes like `_list` on `SortedList` or `SortedSet` was removed in version 2.0.0. Code that relied on these internal implementations will break.
- gotcha Modifying mutable elements *in-place* within a `SortedList` or `SortedSet` can corrupt the collection's sort order if the modification changes the element's comparison value. The collection will not automatically re-sort.
- gotcha While highly optimized, many operations (e.g., insertion, deletion, lookup by value) on `SortedList`, `SortedSet`, and `SortedDict` have logarithmic time complexity (O(log N)) due to the necessity of maintaining sorted order. This differs from O(1) for some operations in standard, unsorted `list` or `dict`.
Install
-
pip install sortedcollections
Imports
- SortedList
from sortedcollections import SortedList
- SortedDict
from sortedcollections import SortedDict
- SortedSet
from sortedcollections import SortedSet
Quickstart
from sortedcollections import SortedDict
sd = SortedDict()
sd[5] = 'apple'
sd[1] = 'banana'
sd[3] = 'cherry'
print(f"SortedDict items: {list(sd.items())}")
# Expected output: SortedDict items: [(1, 'banana'), (3, 'cherry'), (5, 'apple')]
# Example with SortedList
from sortedcollections import SortedList
sl = SortedList([5, 1, 3, 2, 4])
sl.add(0)
print(f"SortedList: {list(sl)}")
# Expected output: SortedList: [0, 1, 2, 3, 4, 5]