4
>>> d = {'A':1, 'b':2, 'c':3, 'D':4}

>>> d
{'A': 1, 'D': 4, 'b': 2, 'c': 3}

>>> d.items()
[('A', 1), ('c', 3), ('b', 2), ('D', 4)]

Does the order get randomized twice when I call d.items()? Or does it just get randomized differently? Is there any alternate way to make d.items() return the same order as d?

Edit: Seems to be an IPython thing where it auto sorts the dict. Normally dict and dict.items() should be in the same order.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Kevin
  • 977
  • 1
  • 10
  • 17
  • 6
    A dict doesn't have an inherent order, the specific order of its elements is an implementation detail and depends on the history of the dict. If order matters, use an ordered dict. If it doesn't matter, don't rely on it. – Andras Deak -- Слава Україні Sep 04 '16 at 20:56
  • 1
    The order of d.keys() and d.items() will match though ([ref](http://stackoverflow.com/q/835092/2285236)) – ayhan Sep 04 '16 at 20:58
  • Can't reproduce. Both `d` and `d.items()` show up in the same order when I try it. Are you sure these were actually the same dict in your test? Are you sure you didn't do anything to the dict between the statements shown? – user2357112 Sep 04 '16 at 21:01
  • Were the lines you show in the question all run in the same interpreter session? Recent versions of Python randomize the hashes of strings so the order you'll see the keys in a dictionary (even one created exactly the same way) will differ between sessions. – Blckknght Sep 04 '16 at 21:07
  • @user2357112 I can reproduce: http://i.imgur.com/qsX5lAK.png (Python 3.5.2) – ayhan Sep 04 '16 at 21:07
  • @ayhan: Strange. I wonder if that's an IPython thing. – user2357112 Sep 04 '16 at 21:13
  • 3
    Further testing seems to indicate this is an IPython-specific thing. – user2357112 Sep 04 '16 at 21:15
  • Incidentally, if you ran this through IPython and then edited the output to look like a regular Python interactive session, please don't do that. It makes it much harder to help you when a problem turns out to be IPython-specific. – user2357112 Sep 04 '16 at 21:23

1 Answers1

10

You seem to have tested this on IPython. IPython uses its own specialized pretty-printing facilities for various types, and the pretty-printer for dicts sorts the keys before printing (if possible). The d.items() call doesn't sort the keys, so the output is different.

In an ordinary Python session, the order of the items in the dict's repr would match the order of the items from the items method. Dict iteration order is supposed to be stable as long as a dict isn't modified. (This guarantee is not explicitly extended to the dict's repr, but it would be surprising if the implicit iteration in repr broke consistency with other forms of dict iteration.)

user2357112
  • 260,549
  • 28
  • 431
  • 505