2

I have a set of characters (x) that is ordered as I need it:

{'a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'j',
 'k',
 'l',
 'm',
 'n',
 'o',
 'p',
 'q',
 'r',
 's',
 't',
 'u',
 'v',
 'w',
 'x',
 'y',
 'z'}

However, when I attempt to convert these back to a string using the .join() function:

return ' '.join(x)

The characters are being randomly reordered:

'c g e w i z n t l a q h p d f v m k b x u r j o y'

Any ideas as to what's going on here?

abc6789
  • 21
  • 1

2 Answers2

2

Sets don't "promise" to maintain order, sometimes they do, but they shouldn't be used with a dependency on it. Furthermore, consider using the following:

alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Then:

return " ".join(alpha)

However, if you only care about it being in alphabetical and want to use a set you can force it to be sorted before using the join function...

return " ".join(sorted(x))

Good luck!

Blonded
  • 137
  • 1
  • 11
-1

Sets and dictionaries are unordered (pre Python 3.7). Their exact implementation involves hashtables and can be a little complicated. However, suffice it to say that the order you put elements into the set does not determine the order they are stored.

You can use OrderedDict or you can convert the set to a list, sort, and go from there.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25