Python has an ordered dictionary. What about an ordered set?
Python is a versatile programming language with a few options for creating ordered sets. You can use the OrderedSet class to get the job done, or you can do so manually if needed.
Due to changes in dict implementation in Python 3.6 it is now ordered by default.
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Python Lists. The important characteristics of Python lists are as follows: Lists are ordered. Lists can contain any arbitrary objects.
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:
@staticmethod def union(*sets): union = OrderedSet() union.union(*sets) return union 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'] >>> list(dict.fromkeys(keywords)) ['foo', 'bar', 'baz']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With