python - 在 Python 中对字典实现 for 循环

标签 python

Possible Duplicate:
python looping seems to not follow sequence?
In what order does python display dictionary keys?

d = {'x': 9, 'y': 10, 'z': 20}
for key in d: 
    print d[key]

上面的代码每次运行时都会给出不同的输出。并不是完全不同的输出,而是以不同的顺序输出。我使用 Aptana 3 多次执行代码。

第一次执行给出: 10 9 20

第二次执行给出: 20 10 9

我还在在线 IDE 中执行了代码 http://labs.codecademy.com 。输出始终是 10 9 20

我只是想知道这是为什么。理想情况下,每次执行上述代码时,它应该打印 9 10 20。请解释。

最佳答案

字典是键到值的映射;它没有订单。

您想要一个collections.OrderedDict:

collections.OrderedDict([('x', 9), ('y', 10), ('z', 20)])
Out[175]: OrderedDict([('x', 9), ('y', 10), ('z', 20)])

for key in Out[175]:
    print Out[175][key]

但是请注意,字典排序是确定性的——如果您迭代同一字典两次,您将得到相同的结果。

关于python - 在 Python 中对字典实现 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14626189/

相关文章:

python - 将 python 代码放到网上 - 与我的 app.py 脚本混淆

python - 矢量化照片 : Finding an Adapted Algorithm

python导入sqlite错误

python - 回调 celery apply_async

python - 在 python 中使用 "or"赋值

python - 如何在 scipy 中模拟 2 样本 t 检验

python - 如何使 Toplevel() 小部件出现在主根窗口上方?

python - 我可以将目标函数和导数函数作为一个函数传递给 scipy.optimize.minimize 吗?

python - keras:使用get_weights函数提取权重

python - 消除列表中重复项但保持先前相对顺序的最佳方法