Does Python have an ordered set?

前端 未结 14 1364
予麋鹿
予麋鹿 2020-11-21 13:20

Python has an ordered dictionary. What about an ordered set?

14条回答
  •  失恋的感觉
    2020-11-21 13:56

    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']
    

提交回复
热议问题