I know from other posts on this site that (1) sets in python are not ordered but (2), in modern versions of Python a good way to get an ordered set is to use a dictionary (which now preservers key/value insertion order) with None
values. This seems fine, but is there an easy way to get an ordered set which has the same API as a regular set? For example with a set I do
color_set = set()
color_set.add('red')
color_set.add('blue')
color_set.add('red')
color_set.add('yellow')
With a dictionary I do
color_set = dict()
color_set['red'] = None
color_set['blue'] = None
color_set['red'] = None
color_set['yellow'] = None
The syntax is different. I suppose I could do:
class OrderedSet(dict):
def add(self, value)
self[value] = None
But what if there are other features of set
that I would like OrderedSet
to have? Do I just need to maintain my own OrderedSet
class and add features as I go? Is there a simple way to realize OrderedSet
with the same API as set
?
CodePudding user response:
You can check out the ordered set library. First install it using pip install ordered-set
.
Then you can do this,
from ordered_set import OrderedSet
color_set = OrderedSet()
color_set.add('red')
color_set.add('blue')
color_set.add('red')
color_set.add('yellow')
The output will be,
OrderedSet(['red', 'blue', 'yellow'])
It has the other basic functions that python sets has as well and other maintain it so you don't have to.