There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
OrderedSet([1, 2, 3])
This is a MutableSet, so the signature for .union doesn’t match that of set, but since it includes __or__ something similar can easily be added:
union = OrderedSet()
def union(self, *sets):
for set in sets:
self |= set
The answer is no, but you can use collections.OrderedDict from the Python standard library with just keys (and values as None) for the same purpose.
Update: As of Python 3.7 (and CPython 3.6), standard dict is guaranteed to preserve order and is more performant than OrderedDict. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict.)
Here’s an example of how to use dict as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict class method fromkeys() to create a dict, then simply ask for the keys() back.
>>> keywords = [‘foo’, ‘bar’, ‘bar’, ‘foo’, ‘baz’, ‘foo’]
[‘foo’, ‘bar’, ‘baz’]