我知道python dict是次序少,但是为什么我以相同的顺序获得密钥“总是” [英] I know python dict is order less but why I am getting keys in same order "always"

查看:94
本文介绍了我知道python dict是次序少,但是为什么我以相同的顺序获得密钥“总是”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dict 命名为 tmp

>>> tmp
{1: 'ONE', 2: 'TWO', 3: 'THREE'}
>>> type(tmp)
<type 'dict'>

我重复了这个 dict 二十次,在所有的迭代中,我按相同的顺序列出了密钥列表。

I iterated through this dict twenty times and on all iterations I got keys list in same order.

>>> for i in range(20):
...   print tmp.keys()
... 
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

我知道python dict是次序少为什么我在相同的顺序永远

I know python dict is order less but why I am getting keys in same order "always"?

推荐答案

您不修改 tmp 之间调用 tmp.keys(),所以键的顺序从不改变。

You don't modify tmp between calls to tmp.keys(), so the order of the keys never changes.

从文档:


如果 items() keys() values() iteritems() iterkeys() itervalues()被称为w没有对字典的干预修改,列表将直接对应。这允许使用 zip()创建(value,key)对: pairs = zip(d.values(),d.keys())。相同的关系适用于 iterkeys() itervalues()方法: pairs = zip (d.itervalues(),d.iterkeys())为对提供相同的值。创建相同列表的另一种方式是在d.iteritems()]中的(k,v)的 pairs = [(v,k)]

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

这篇关于我知道python dict是次序少,但是为什么我以相同的顺序获得密钥“总是”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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