简体   繁体   English

为什么dict和dict.items()的顺序不同?

[英]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()? 当我调用d.items()时,顺序是否会随机化两次? Or does it just get randomized differently? 还是只是以不同的方式随机化? Is there any alternate way to make d.items() return the same order as d? 有没有其他方法可以使d.items()返回与d相同的顺序?

Edit: Seems to be an IPython thing where it auto sorts the dict. 编辑:似乎是IPython事物,它会自动对字典进行排序。 Normally dict and dict.items() should be in the same order. 通常,dict和dict.items()的顺序应相同。

You seem to have tested this on IPython. 您似乎已经在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). IPython对各种类型使用自己专用的漂亮打印工具,并且dict漂亮打印器在打印之前对键进行排序(如果可能)。 The d.items() call doesn't sort the keys, so the output is different. d.items()调用不会对键进行排序,因此输出是不同的。

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. 在普通的Python会话中,字典repr中的项目顺序将与items方法中的项目顺序匹配。 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.) (此保证没有明确扩展到dict的repr ,但是如果repr的隐式迭代破坏了与其他形式的dict迭代的一致性,这将是令人惊讶的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM