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

示例输入:

{2:3, 1:89, 4:5, 3:0}

期望的输出:

{1:89, 2:3, 3:0, 4:5}

当前回答

正如其他人所提到的,字典本质上是无序的。然而,如果问题只是以有序的方式显示字典,你可以在字典子类中重写__str__方法,并使用这个字典类而不是内置的字典。如。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}

注意,这不会改变键的存储方式,当你遍历它们时它们返回的顺序等,只是它们在打印时或在python控制台中显示的方式。

其他回答

Python字典在Python 3.6之前是无序的。在Python 3.6的CPython实现中,字典保持插入顺序。 从Python 3.7开始,这将成为一种语言特性。

在Python 3.6的更新日志(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):

考虑了这个新实现的保序方面 一个实现细节,不应该依赖(这可能 将来会有变化,但希望有这个新词典 在语言中实现了几个版本,然后才更改 语言规范要求所有当前的语义保持有序 以及未来的Python实现;这也有助于保存 向后兼容该语言的旧版本 随机迭代顺序仍然有效,例如Python 3.5)。

Python 3.7文档(https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):

在字典上执行list(d)将返回所有使用的键的列表 在字典中,按插入顺序(如果你想排序,只需使用 排序(d))。

因此,与以前的版本不同,您可以在Python 3.6/3.7之后对字典进行排序。如果你想对包含子字典在内的嵌套字典进行排序,你可以这样做:

test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}

def dict_reorder(item):
    return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}

reordered_dict = dict_reorder(test_dict)

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

简单:

d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())

for k,v in sd:
    print k, v

输出:

1 89
2 3
3 0
4 5
dictionary = {1:[2],2:[],5:[4,5],4:[5],3:[1]}

temp=sorted(dictionary)
sorted_dict = dict([(k,dictionary[k]) for i,k in enumerate(temp)])

sorted_dict:
         {1: [2], 2: [], 3: [1], 4: [5], 5: [4, 5]}

找到了另一种方法:

import json
print json.dumps(d, sort_keys = True)

乌利希期刊指南: 1. 这也可以对嵌套对象进行排序(谢谢@DanielF)。 2. Python字典是无序的,因此只适用于打印或赋值给STR。

对于CPython/PyPy 3.6,以及任何Python 3.7或更高版本,这很容易做到:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}