pythondictionaryset

Python how to get ordered set with the same API as regular set?


(1) sets in python are not ordered but (2), in modern Python a good way to get an ordered set is to use a dictionary (which now preservers key/value insertion order) with None values. Are there ordered sets which have the same API as a regular set? For example:

color_set = set()
color_set.add('red')
color_set.add('blue')
color_set.add('red')
color_set.add('yellow')

color_set = dict()
color_set['red'] = None
color_set['blue'] = None
color_set['red'] = None
color_set['yellow'] = None

The syntax is different. I could do:

class OrderedSet(dict):
    def add(self, value)
        self[value] = None

If there are other features of set that I would like, must I maintain a OrderedSet class? Is there a simple way to realize OrderedSet with the same API as set?


Solution

  • 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.