1

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?

Jagerber48
  • 488
  • 4
  • 13
  • 1
    Do you explore this lib - https://pypi.org/project/ordered-set/ ? – Daniel Hao Oct 10 '22 at 21:09
  • 1
    One of the [answers](/a/23225031/90527) to the [canonical question](/q/1653970/90527) lists modules than implement standard set operations and at least most of the `set` interface. – outis Oct 10 '22 at 22:07

1 Answers1

2

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.

anarchy
  • 3,709
  • 2
  • 16
  • 48