为什么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)]
当我调用d.items()时,订单是否会被随机化两次?或者只是以不同方式随机化?是否有任何替代方法使d.items()返回与d相同的顺序?
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?
编辑:似乎是一个自动排序dict的IPython事物。通常dict和dict.items()应该是相同的顺序。
Seems to be an IPython thing where it auto sorts the dict. Normally dict and dict.items() should be in the same order.
推荐答案
你似乎已经在IPython上测试了这个。 IPython使用自己专门针对各种类型的漂亮打印设备,而用于dicts的漂亮打印机在打印前对键进行排序(如果可能)。 d.items()
调用不对键进行排序,因此输出不同。
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.
普通的Python会话,dict的 repr
中项目的顺序将与 items
方法中的项目顺序相匹配。只要不修改dict,Dict迭代顺序就应该是稳定的。 (此保证未明确扩展到dict的 repr
,但如果 repr
中的隐式迭代中断,则会令人惊讶与其他形式的dict迭代的一致性。)
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.)
这篇关于为什么dict和dict.items()的顺序不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!