Python Sorted Collections

2.1.0 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

Demonstrates the creation and basic usage of SortedDict and SortedList, showing how elements are automatically kept in sorted order upon insertion.

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]

view raw JSON →