0

I have been trying to study the simplest of things and would appreciate if someone explains why this behaves the way it does. Code snippet below:

#Creating dict from set using enumerate:

    myset = {'A','A','B','C'}
    mydict = dict(enumerate(myset))
    print(mydict)

Output:

    {0: 'B', 1: 'C', 2: 'A'}

My Expected Output:

    {0: 'A', 1: 'B', 2: 'C'}

Whereas, it works fine with lists!

#Creating dict from list using enumerate:

    li = ["apple","banana","mango"]
    mydict = dict(enumerate(myset))
    print(mydict)

Output:

    {0: 'apple', 1: 'banana', 2: 'mango'}

Explanation appreciated!

  • The order of elements in a set is unspecified, and CPython deliberately shuffles it to prevent you from depending on consistent ordering. – Barmar Mar 18 '21 at 16:37
  • 1
    @Barmar: Are you thinking of Go maps or something? There's no deliberate shuffling in a CPython set. – user2357112 Mar 18 '21 at 16:43
  • @user2357112supportsMonica I thought I remembered a question where someone ran code like this repeatedly, and got a different order each time. – Barmar Mar 18 '21 at 16:44
  • @Barmar: You might be thinking of the effects of hash randomization - a few built-in types have hashes that depend on random state initialized at interpreter setup. This is intended to make hash collision attacks more difficult. – user2357112 Mar 18 '21 at 16:45

1 Answers1

0

Sets do not have order, but lists do. That's why when you enumerate the set it doesn't do it in your intended order. More info can be found in the official documentation.