如何按值对字典进行排序

如何按值对字典进行排序

技术背景

在Python编程中,字典是一种无序的数据结构,有时我们需要根据字典的值对其进行排序。由于字典本身无序,所以我们通常需要借助其他数据结构或方法来实现按值排序的需求。

实现步骤

Python 3.7+ 或 CPython 3.6

在Python 3.7+ 以及 CPython 3.6 中,字典会保留插入顺序。可以使用以下方法按值排序:

1
2
3
4
5
6
7
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# 方法一
sorted_dict1 = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(sorted_dict1)
# 方法二
sorted_dict2 = dict(sorted(x.items(), key=lambda item: item[1]))
print(sorted_dict2)

旧版本Python

在旧版本的Python中,字典本身无法排序,只能获取其排序后的表示。可以使用列表(通常是元组列表)来表示排序后的值。

1
2
3
4
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
print(sorted_x)

使用 collections.OrderedDict

如果需要将排序结果作为字典输出,可以使用 collections.OrderedDict

1
2
3
4
5
import collections
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
sorted_dict = collections.OrderedDict(sorted_x)
print(sorted_dict)

使用 sorted(d, key=d.get)

可以使用 sorted(d, key=d.get) 对字典的键进行排序,排序依据是键对应的值。

1
2
3
4
5
6
7
8
from collections import defaultdict
text = "hello world hello python"
d = defaultdict(int)
for w in text.split():
d[w] += 1

for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])

使用 Counter

如果字典的值是数值类型,可以使用 collections.Counter 进行排序。

1
2
3
4
5
6
7
8
9
10
11
from collections import Counter
x = {'hello': 1, 'python': 5, 'world': 3}
c = Counter(x)
# 降序排序
print(c.most_common())
# 升序排序
print(c.most_common()[::-1])
# 转换为 OrderedDict
from collections import OrderedDict
sorted_dict = OrderedDict(c.most_common()[::-1])
print(sorted_dict)

核心代码

以下是几种常见的按值排序字典的核心代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Python 3.7+ 或 CPython 3.6
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict = dict(sorted(x.items(), key=lambda item: item[1]))
print(sorted_dict)

# 旧版本 Python
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
print(sorted_x)

# 使用 OrderedDict
import collections
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
sorted_dict = collections.OrderedDict(sorted_x)
print(sorted_dict)

# 使用 sorted(d, key=d.get)
from collections import defaultdict
text = "hello world hello python"
d = defaultdict(int)
for w in text.split():
d[w] += 1

for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])

# 使用 Counter
from collections import Counter
x = {'hello': 1, 'python': 5, 'world': 3}
c = Counter(x)
print(c.most_common())
print(c.most_common()[::-1])
from collections import OrderedDict
sorted_dict = OrderedDict(c.most_common()[::-1])
print(sorted_dict)

最佳实践

  • 选择合适的 Python 版本:如果使用 Python 3.7+ 或 CPython 3.6,可以直接使用字典的插入顺序特性进行排序。
  • 根据需求选择数据结构:如果需要保留排序顺序,可以使用 OrderedDict;如果字典的值是数值类型,可以使用 Counter
  • 使用 key 参数:在使用 sorted 函数时,通过 key 参数指定排序依据,提高代码的可读性和灵活性。

常见问题

字典本身是否可以排序?

字典是无序的数据结构,本身无法排序。但可以通过将其转换为有序的数据结构(如列表、OrderedDict)来实现排序的效果。

排序结果是否稳定?

使用 sorted 函数进行排序时,排序结果是稳定的,即值相同的元素在排序后保持原来的相对顺序。

如何进行降序排序?

sorted 函数中添加 reverse=True 参数即可实现降序排序。例如:

1
2
3
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict = dict(sorted(x.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)

如何按值对字典进行排序
https://119291.xyz/posts/2025-05-09.how-to-sort-a-dictionary-by-value/
作者
ww
发布于
2025年5月9日
许可协议