python - 如何按键对字典进行排序?

标签 python sorting dictionary

如何按字典键对字典进行排序?

输入示例:

{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/

相关文章:

java - 将两张 map 合并为第三张

arrays - Swift:从 View 层次结构创建平面 View 数组

Python:使用列表值添加到字典的最佳方式

python - 用字符串键构造字典时,我应该在 Python 中写 dict 还是写 {}?

python - 如何使用正则表达式提取文本 block 而不将文本 block 分成几行

python - 在文件中存储大型 python 字典的最佳方法

c++ - std::sort with equal elements 给出段错误

python - 在 Flask 模板中处理 HTML5 列表中的空格

javascript - 修复 Angular 排序

ios - 按编号对解析对象进行排序