python - Why is the order of dict and dict.items() different? -


>>> 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 order randomized twice when call d.items()? or randomized differently? there alternate way make d.items() return same order d?

edit: seems ipython thing auto sorts dict. dict , dict.items() should in same order.

you seem have tested on ipython. ipython uses own specialized pretty-printing facilities various types, , pretty-printer dicts sorts keys before printing (if possible). d.items() call doesn't sort keys, output different.

in ordinary python session, order of items in dict's repr match order of items items method. dict iteration order supposed stable long dict isn't modified. (this guarantee not explicitly extended dict's repr, surprising if implicit iteration in repr broke consistency other forms of dict iteration.)


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -