Lily567
Lily567

Reputation: 11

Why does order of elements in a set differ in py2 and py3?

In py2:

{1: {“1”, “2”, “7”, “3”, “4”, “9”, “8”}}

Returns for all runs {1: set([‘1’, ‘3’, ‘2’, ‘4’, ‘7’, ‘9’, ‘8’])}

In py3:

{1: {“1”, “2”, “7”, “3”, “4”, “9”, “8”}}

Returns for first run {1: {“1”, “3”, “4”, “7”, “8”, “2”, “9”}}

Returns for second run {1: {“2”, “4”, “9”, “7”, “1”, “3”, “8”}} Order of items in inside dict keeps changing.

My main question is why does it keep changing with every run and how to resolve it so that returns a stable result as in py2?

Upvotes: 1

Views: 57

Answers (1)

matszwecja
matszwecja

Reputation: 7971

Use a different structure (like a list or dict (since Python 3.7)/OrderedDict) - sets inherently don't have a concept of order.

Upvotes: 1

Related Questions