2

Looking to join two set as an append without sorting.

Here is my code:

a = {123,456,789}
b = {777,888}
a = a.union(b)
a

Output:

{123, 456, 777, 789, 888}

Desired output:

{123, 456, 789, 777, 888}

Thanks!

Mick
  • 265
  • 2
  • 10

2 Answers2

3

Sets are unordered so you can't guarantee an arrangement. The answer from BEN_YO will make it so the second sets elements are at the end but the internal ordering will differ, as shown in his sample output.

If ordering matters you need to use a different collection type. A quick hack if you want both ordering and uniqueness would be to use a dictionary, as in modern python dictionary keys are ordered and unique.

a = {123: '',456: '',789: ''}
b = {777: '',888: ''}

a = {**a, **b}

Although then you can't use faster merge operations like union so it may not be an ideal solution.

Further Reading
  • 233
  • 2
  • 8
  • *as in modern python dictionary keys are ordered and unique* can you provide a reference? I thought that's what `OrderedDict` is for and dictionary keys are essentially sets. – Quang Hoang Oct 15 '20 at 00:27
  • 1
    Been this way officially since 3.7, unoffically since 3.6. https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – Further Reading Oct 15 '20 at 00:29
1

If we need the order

a = {123,456,789}
b = {777,888}
a = list(a)+[i for i in b if i not in a]

a
Out[58]: [456, 123, 789, 888, 777]


panda method unique

pd.Series(list(a)).append(pd.Series(list(b))).unique()
Out[66]: array([456, 123, 789, 888, 777], dtype=int64)
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thanks @BEN. Any possible way to keep it as a set, and the order as per my desired output? – Mick Oct 15 '20 at 00:21
  • 1
    @Mick set will change the order by itself, if want set, you can not keep the original order . And I would do list ~ – BENY Oct 15 '20 at 00:23