11

I am trying to sort a set in python, by adding elements to it. I tried using the sorted() method, but it is converting my set into a list. I need to sort my elements and print it as a set itself. How can I do that?

I tried using the sorted() method and obtained a list. Tried to put the list into a set. But, didn't receive the required result

a={}
a=set()
a.add(1)
a.add(-1)
a.add(0)
a.add(4)
a.add(-3)
print(a)

Expected result: {-3, -1, 0, 1, 4} Actual result: {0, 1, 4, -3, -1}

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Peyton
  • 127
  • 1
  • 1
  • 5
  • 3
    sets don't have order, if you want an ordered collection, a list could be a good way to go – Henry Woody Mar 28 '19 at 02:10
  • 3
    `set`'s are unordered. They don't have an order. You could use `OrderedDict` or just `dict` in Python 3.7+ if you like. – iz_ Mar 28 '19 at 02:10
  • @Tomothy32 Just noting here that the `dict` in Python3.6 and above only preserves insertion order in the CPython implementation. – mttpgn Mar 28 '19 at 02:17
  • @mttpgn In 3.6, it's a CPython implementation detail. In 3.7+, it's part of the standard. – iz_ Mar 28 '19 at 02:20

1 Answers1

21

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])
Ender Look
  • 2,303
  • 2
  • 17
  • 41