Categories
Python Answers

How to create an ordered set with Python?

Spread the love

Sometimes, we want to create an ordered set with Python.

In this article, we’ll look at how to create an ordered set with Python.

How to create an ordered set with Python?

To create an ordered set with Python, we can create a list from dict keys.

For instance, we write

keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']
l = list(dict.fromkeys(keywords))

to get a dict with keys created from the keywords list.

And then we can convert the dict returned to a list with list.

As a result, we get ['foo', 'bar', 'baz'] as the value of l.

Conclusion

To create an ordered set with Python, we can create a list from dict keys.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *