Python字典迭代顺序被意外排序。为什么? [英] Python dictionary iteration order is unexpectedly sorted. Why?

查看:262
本文介绍了Python字典迭代顺序被意外排序。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个字典用连续的整数键填充,如下所示:

A dictionary is populated with consecutive integer keys, like this:

d = dict()
for i in range(0, 10):
    d[i] = 100-i

字典项目被这样迭代:

for k, v in d.items():
    print k, v

结果显示项目按数字顺序迭代:

The result shows the items are iterated in numerical order:

0 100
1 99
2 98
3 97
4 96
5 95
6 94
7 93
8 92
9 91

事实证明,这是我想要的行为,但不是我的预期。我希望以随机顺序进行字典迭代。这里发生了什么,我可以依赖于公开发布的代码中的这种行为吗?

It turns out, this is the behavior I want, but not what I expected. I expected dictionary iteration in random order. What's going on here, and can I depend on this behavior in code released publicly?

推荐答案

字典不是随机的。它们位于任意订单。在这种情况下,你很幸运,他们被排序。明天,他们可能不会。如果需要随机性,请使用 random 。如果您需要排序顺序,请使用 sorted()。如@BenjaminWohlwend在评论中提到的,您可以使用 collections.OrderedDict 来跟踪插入顺序。

Dictionaries are not in random order. They are in arbitrary order. In this case, you got lucky and they were sorted. Tomorrow, they might not be. If you need randomness, use random. If you need sorted order, use sorted(). As @BenjaminWohlwend mentions in the comments, you can use collections.OrderedDict to keep track of insertion order.

在这种情况下,我会猜测字典正在做一些小整数键优化,像一个数组(例如 hash(1)== 1 )。这不是一个保证的行为,并且可能在其他Python实现上有所不同。

In this case, I would guess the dictionary is doing some sort of small-integer-key optimization, acting like an array (e.g. hash(1) == 1). This is not a guaranteed behavior and might work differently on other Python implementations.

这篇关于Python字典迭代顺序被意外排序。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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