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

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    (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?

    Continue reading...

Compartilhe esta Página