Python has an ordered dictionary. What about an ordered 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']
A little late to the game, but I've written a class setlist
as part of collections-extended
that fully implements both Sequence
and Set
>>> from collections_extended import setlist
>>> sl = setlist('abracadabra')
>>> sl
setlist(('a', 'b', 'r', 'c', 'd'))
>>> sl[3]
'c'
>>> sl[-1]
'd'
>>> 'r' in sl # testing for inclusion is fast
True
>>> sl.index('d') # so is finding the index of an element
4
>>> sl.insert(1, 'd') # inserting an element already in raises a ValueError
ValueError
>>> sl.index('d')
4
GitHub: https://github.com/mlenzen/collections-extended
Documentation: http://collections-extended.lenzm.net/en/latest/
PyPI: https://pypi.python.org/pypi/collections-extended