python dict key顺序_“for key in dict”在python中总是以固定顺序迭代?

Does the python code

for key in dict:

...

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

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

One of the few reliable ways:

for key in sorted(yourDictionary.keys()):

# Use as key and yourDictionary[key]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值