问题描述
从 {2:3,1:89,4:5,3:0}
到 { 1:89,2:3,3:0,4:5}
?
我检查了一些帖子,但都使用返回元组的sorted运算符。
标准Python字典无序。即使您对(键,值)对进行了排序,也无法将它们存储在 dict
中,以保持排序的方式。
最简单的方法是使用,它记住插入元素的顺序:
在[ 1]:导入集合
在[2]中:d = {2:3,1:89,4:5,3:0}
在[3] od = collections.OrderedDict(sorted(d.items()))
在[4]中:od
Out [4]:OrderedDict([(1,89) 3),(3,0),(4,5)])
code> od 打印出来;它将按预期工作:
在[11]中:od [1]
/ pre>
输出[11]:89
在[12]中:od [3]
输出[12]:0
在[13]中:对于k,v在od.iteritems() :print k,v
....:
1 89
2 3
3 0
4 5
Python 3
对于Python 3用户,需要使用
.items()
而不是.iteritems()
:code>在[13]中:for k,v in od.items():print(k,v)
....:
1 89
2 3
3 0
4 5
What would be a nice way to go from
{2:3, 1:89, 4:5, 3:0}
to{1:89, 2:3, 3:0, 4:5}
?
I checked some posts but they all use the "sorted" operator that returns tuples.解决方案Standard Python dictionaries are unordered. 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.The easiest way is to use
OrderedDict
, which remembers the order in which the elements have been inserted: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; 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
For Python 3 users, one needs to use the
.items()
instead of.iteritems()
:In [13]: for k, v in od.items(): print(k, v) ....: 1 89 2 3 3 0 4 5
这篇关于如何按键排序字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!