Standard Python dictionaries are unordered.
(标准Python字典是无序的。)
Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict
in a way that would preserve the ordering. (即使您对(键,值)对进行了排序,也无法以保留顺序的方式将它们存储在dict
中。)
The easiest way is to use OrderedDict
, which remembers the order in which the elements have been inserted:
(最简单的方法是使用OrderedDict
,它可以记住元素插入的顺序:)
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Never mind the way od
is printed out;
(没关系od
的打印方式;)
it'll work as expected: (它会按预期工作:)
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3 (Python 3)
For Python 3 users, one needs to use the .items()
instead of .iteritems()
:
(对于Python 3用户,需要使用.items()
而不是.iteritems()
:)
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…