python中"for key in dict"是否总是以固定顺序迭代?

use*_*994 6 python dictionary

是python代码

for key in dict:
    ...
Run Code Online (Sandbox Code Playgroud)

,dictdict数据类型在哪里,总是以regrard的固定顺序迭代到key?例如,假设dict={"aaa":1,"bbb",2}上面的代码总是先让key="aaa"(然后key="bbb"是另一个固定的顺序)?订单是否可能是随机的?我在ubuntu 13中使用python 3.3,让我们假设这个运行环境不会改变.谢谢.

添加一件事:在多次运行期间,变量dict保持不变,即生成一次并多次读取.

Ult*_*nct 10

从本质上讲,字典没有存储密钥的顺序.所以你不能依赖订单.(即使环境相同,我也不会认为订单不变).

少数可靠方法之一:

for key in sorted(yourDictionary.keys()):
    # Use as key and yourDictionary[key]
Run Code Online (Sandbox Code Playgroud)

编辑:对您的评论的回应:Python不以随机方式存储密钥.所有文件都说,你不应该依赖这个订单.这取决于按键的实现方式.我在这里谈到你的问题是:如果你依赖这个命令,你可能做错了什么.一般来说,你应该/根本不需要依赖它.:-)


atu*_*pal 5

CPython implementation detail: Keys and values are listed in an arbitrary \norder which is non-random, varies across Python implementations, and \ndepends on the dictionary\xe2\x80\x99s history of insertions and deletions.\n
Run Code Online (Sandbox Code Playgroud)\n\n

欲了解更多信息:http://docs.python.org/2/library/stdtypes.html#dict.items

\n\n

更重要的是,您可以使用collections.OrderedDict来固定顺序。

\n