Why is the order of dict and dict.items() differen

2019-01-20 13:59发布

>>> 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条回答
等我变得足够好
2楼-- · 2019-01-20 14:01

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

查看更多
登录 后发表回答