How to sort a set in python?

You can’t

Just read python documentation:

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Emphasis mine.

That means you will never be able to sort items inside a set*.

At least, with “normal” sets, you can’t. You should better look for third-party libraries (both, default dictionaries and collections.OrderedDict), because I don’t think that python has inbuilt ordered sets, at least no in collections.

*Well, not never, I have understood that early versions of python hadn’t ordered dictionaries, and now they have. But at least in the current version (python 3.7), there aren’t ordered sets.

Anyway, dictionaries work in a similar manner to sets. In a dictionary, you can’t have two times the same key, like in a set you can’t have two times the same item. So if you work with the keys of a dictionary and just ignore the values of those keys, a collections.OrderedDict may work for you. Even base dictionaries (those you make with dict()) will work since Python 3.7.

>>> a = dict()
>>> a[1] = None
>>> a[-1] = None
>>> a[0] = None
>>> a[4] = None
>>> a[-3] = None
>>> print(a.keys())
dict_keys([1, -1, 0, 4, -3])

Leave a Comment