Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...