“for key in dict”在python中总是以固定顺序迭代? [英] Does "for key in dict" in python always iterate in a fixed order?

查看:785
本文介绍了“for key in dict”在python中总是以固定顺序迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python代码

for key in dict:
    ...

,其中 dict 是一个dict数据类型,始终以固定顺序迭代与regrard到?例如,假设 dict = {aaa:1,bbb,2} ,上述代码将始终先让$ code> key =aaa 然后 key =bbb(或按另一个固定顺序)?订单有可能是随机的吗?我在ubuntu 13中使用python 3.3,我们假设这个运行环境不会改变。谢谢。

, where dict is a dict data type, always iterate in a fixed order with regrard to key? For example, suppose dict={"aaa":1,"bbb",2}, will the above code always first let key="aaa" and then key="bbb" (or in another fixed order)? Is it possible that the order is random? I am using python 3.3 in ubuntu 13 and let's assume this running environment doesn't change. Thank you.

添加一件事:在多次运行中,变量 dict 保持不变,即生成一次,读取多次。

add one thing: during multiple runs, the variable dict remains unchanged, i.e., generate once and read multiple times.

推荐答案

本质上,一个字典没有订单存储它的键。所以你不能依靠订单。 (即使在环境相同的情况下,我也不会认为订单不变)。

Intrinsically, a dictionary has no order in which it stores it keys. So you can not rely on the order. (I wouldn't assume the order to be unchanged even when the environment is identical).

几种可靠的方法之一:

for key in sorted(yourDictionary.keys()):
    # Use as key and yourDictionary[key]

编辑:回复您的评论:
Python不以随机方式存储密钥。所有的文档说明,你不应该依赖这个订单。这取决于按键的执行方式。我将在这里谈到你的问题是:如果你依靠这个命令,你可能会做错事。一般来说,你应该/不需要依靠这一点。 : - )

EDIT: Response to your comment: Python does not store keys in a random fashion. All the documentation says is that, you should not rely on this order. It depends on the implementation how the keys are ordered. What I will say here about your question is: If you are relying on this order, you are probably doing something wrong. In general you should/need not rely on this at all. :-)

这篇关于“for key in dict”在python中总是以固定顺序迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆