如何按字典键对字典进行排序?
输入示例:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
最佳答案
Note: for Python 3.7+, see this answer
标准 Python 字典是无序的(直到 Python 3.7)。即使您对(键,值)对进行排序,您也无法以保留顺序的方式将它们存储在 dict
中。
最简单的方法是使用 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)])
不用介意 od
的打印方式;它会按预期工作:
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 用户,需要使用 .items()
而不是 .iteritems()
:
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
关于python - 如何按键对字典进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653291/