Python字典按键排序的方法
技术背景
在Python中,字典(dict
)在Python 3.6之前是无序的。即使你对字典的(key, value)
对进行排序,也无法以能保留排序顺序的方式将它们存储在dict
中。在Python 3.6的CPython实现中,字典开始保留插入顺序,而从Python 3.7起,这成为了语言特性。不过有时我们仍然需要对字典按键排序,下面将介绍多种实现方法。
实现步骤
Python 2.x 版本
在Python 2.x中,标准的字典是无序的,可使用collections
模块中的OrderedDict
来实现按键排序:
1 2 3 4 5 6 7 8 9 10
| import collections
d = {2: 3, 1: 89, 4: 5, 3: 0}
od = collections.OrderedDict(sorted(d.items()))
print(od)
|
Python 3.x 版本
从Python 3.7起,字典保留插入顺序,可直接使用sorted()
来对字典按键排序:
1 2 3 4 5 6 7 8
| d = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict = dict(sorted(d.items()))
print(sorted_dict)
|
核心代码
使用OrderedDict
1 2 3 4 5
| import collections
d = {2: 3, 1: 89, 4: 5, 3: 0} od = collections.OrderedDict(sorted(d.items())) print(od)
|
Python 3.7及以上使用sorted()
1 2 3
| d = {2: 3, 1: 89, 4: 5, 3: 0} sorted_dict = dict(sorted(d.items())) print(sorted_dict)
|
使用字典推导式
1 2 3
| d = {2: 3, 1: 89, 4: 5, 3: 0} sorted_dict = {k: d[k] for k in sorted(d)} print(sorted_dict)
|
最佳实践
排序嵌套字典
1 2 3 4 5 6 7
| test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item): return {k: dict_reorder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict) print(reordered_dict)
|
使用sortedcontainers
模块
1 2 3 4 5
| from sortedcontainers import SortedDict
d = {2: 3, 1: 89, 4: 5, 3: 0} s = SortedDict(d) print(s.items())
|
常见问题
性能问题
不同的排序方法在性能上有差异。例如,使用sortedcontainers
模块中的SortedDict
通常比其他方法更快,以下是一个性能测试示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import numpy as np from collections import OrderedDict from sortedcontainers import SortedDict import json from timeit import timeit
keys = np.random.rand(100000) vals = np.random.rand(100000)
d = dict(zip(keys, vals))
print(timeit(lambda: SortedDict(d), number=10)) print(timeit(lambda: sorted(d.items()), number=10)) print(timeit(lambda: OrderedDict(sorted(d.items(), key=lambda x: x[0])), number=10)) print(timeit(lambda: dict(sorted(d.items())), number=10)) print(timeit(lambda: OrderedDict(sorted(d.items())), number=10)) print(timeit(lambda: json.dumps(d, sort_keys=True), number=1))
|
不同Python版本的兼容性问题
在Python 2.x中,需要使用collections.OrderedDict
来保留排序顺序,而Python 3.7及以上版本可直接使用sorted()
和dict()
组合来排序。同时,Python 2.x使用.iteritems()
方法迭代,Python 3.x使用.items()
方法。