Python Ordered Set
Python provides an ordered dictionary, but lacks an explicit ordered set. However, as of Python 3.7, the standard library's dict can be employed as an ordered set using only keys and discarding values.
Using dict as an Ordered Set
To emulate an ordered set using dict, simply create a dict with keys and set the values to None. To retrieve the ordered set, access the dict's keys().
keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo'] ordered_set = list(dict.fromkeys(keywords)) # ['foo', 'bar', 'baz']
Pre-Python 3.7: Using collections.OrderedDict
For older Python versions, the collections.OrderedDict object is available for creating ordered sets.
from collections import OrderedDict ordered_set = OrderedDict() for keyword in keywords: ordered_set[keyword] = None
The above is the detailed content of How Can I Implement an Ordered Set in Python?. For more information, please follow other related articles on the PHP Chinese website!