We have gone through set and frozenset in python. Now, can you create an Ordered Set in Python ?
By ordered set, we mean a set that preserves the order in which keys and values are inserted into it.
There are two ways in which we can do it –
- Python 3.7
- Prior to Python 3.7
Creating Ordered Set in Python 3.7+
We can use fromkeys() from dictionary and list() to obtain the desired result.
keywords = ['hello', 'aurav', 'hello', 'narendra', 'foo', 'foo'] sampleList = list(dict.fromkeys(keywords)) print(type(sampleList)) for item in sampleList: print(item)
Here, we have used dictionary as an ordered set to filter out duplicate items while preserving order. Hence, emulating an ordered set.
fromkeys() creates a dictionary using keys present in keywords. Then, we are creating list with keys present in new dictionary.
When you run above program, output is –
<class 'list'> hello aurav narendra foo
First line shows data type of sampleList. Remaining lines show values present in sampleList list. Notice that duplicate keys have been removed.
As for Python 3.7+, dict is ordered by definition.
Creating Ordered Set Using OrderedDict
To implement ordered set prior to python 3.7, we use collections.OrderedDict with keys and all values as None.
from collections import OrderedDict keywords = ['hello', 'aurav', 'hello', 'narendra', 'foo', 'foo'] sampleList = OrderedDict.fromkeys(keywords) print(type(sampleList)) for item in sampleList: print(item)
OrderedDict.fromkeys creates an ordered dict using keys present in keywords list.
<class 'collections.OrderedDict'> hello aurav narendra foo
First line shows data type of sampleList. Remaining lines shows keys present in sampleList OrderedSet. Notice that only unique values are present in sampleList OrderedDict. This is what we wanted to achieve.
Having explained above, if you want to create ordered set and support backward compatibility, you can use OrderedDict.
That’s end of our post on How to Create an Ordered Set in Python.
You can visit official documentation for more detail.