Python has an ordered dictionary. What about an ordered set?
As other answers mention, as for python 3.7+, the dict is ordered by definition. Instead of subclassing OrderedDict
we can subclass abc.collections.MutableSet
or typing.MutableSet
using the dict's keys to store our values.
class OrderedSet(typing.MutableSet[T]):
"""A set that preserves insertion order by internally using a dict."""
def __init__(self, iterable: t.Iterator[T]):
self._d = dict.fromkeys(iterable)
def add(self, x: T) -> None:
self._d[x] = None
def discard(self, x: T) -> None:
self._d.pop(x)
def __contains__(self, x: object) -> bool:
return self._d.__contains__(x)
def __len__(self) -> int:
return self._d.__len__()
def __iter__(self) -> t.Iterator[T]:
return self._d.__iter__()
Then just:
x = OrderedSet([1, 2, -1, "bar"])
x.add(0)
assert list(x) == [1, 2, -1, "bar", 0]
I put this code in a small library, so anyone can just pip install
it.