我知道python dict是次序少,但是为什么我以相同的顺序获得密钥“总是” [英] I know python dict is order less but why I am getting keys in same order "always"
问题描述
我有一个 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()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of(value, key)
pairs usingzip()
:pairs = zip(d.values(), d.keys())
. The same relationship holds for theiterkeys()
anditervalues()
methods:pairs = zip(d.itervalues(), d.iterkeys())
provides the same value for pairs. Another way to create the same list ispairs = [(v, k) for (k, v) in d.iteritems()]
.
这篇关于我知道python dict是次序少,但是为什么我以相同的顺序获得密钥“总是”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!