-2
my_dict = {"one":1, "two":2, "three":3}
print(my_dict)

I'm a newbie. I'm told that dictionaries are unordered, yet the output is still in an order of one kind or another...it is reversed here.

Why, in an apparently unordered dictionary, is the output of the above code as follows?

{'three': 3, 'two': 2, 'one': 1}

If someone could explain I'd be most grateful.

Thanks.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Fiddy Bux
  • 703
  • 11
  • 22
  • 2
    "unordered" and "prints in a random order every time" are not the same thing. "unordered" means "you can not rely on a specific order". – Tomalak Sep 11 '17 at 09:39
  • If you want to go into the nitty gritties and nitpick, you can say a dictionary is "ordered", but you have no control over what the order is. – cs95 Sep 11 '17 at 09:39
  • As for the duplicate(s), I suppose I should have searched, but as I'm on the Android app I expected a dup search upon post creation. When this wasn't forthcoming I wrongly assumed it wasn't a dup. – Fiddy Bux Sep 11 '17 at 10:43

1 Answers1

1

"unordered" means that the order is arbitrary and non significant, not that it's purely random. This order depends on how the keys are internally stored by the underlying implementation, and has already changed quite a few times since the 1.5.x days. You should never assume anything about this order, except that dict.keys() and dict.values() will stay in sync, ie the assertion:

all(dict.values()[x] == dict[dict.keys()[x]] for x in range(len(dict)))

will always be true.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118