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

浪子不回头ぞ 提交于 2019-12-17 20:54:07

问题


>>> 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.


回答1:


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.)



来源:https://stackoverflow.com/questions/39321424/why-is-the-order-of-dict-and-dict-items-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!