Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Sắp xếp Dictionary theo value trong Python

Dùng sorted(dict.items(), key=lambda kv: kv[1]) sắp xếp theo value, sau đó tạo dict mới (Python 3.7+ giữ thứ tự).

Ví dụ

from collections import OrderedDict

D = {5: 'fff', 3: 'ttt', 1: 'ooo', 4: 'bbb', 2: 'ddd'}

# Tăng dần theo value
sorted_items = sorted(D.items(), key=lambda t: t[1])
D_sorted = dict(sorted_items)
print(D_sorted)  # {4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}

# Giảm dần
D_desc = dict(sorted(D.items(), key=lambda t: t[1], reverse=True))

Python 3.7+: dict thường đã giữ insertion order

# Không cần OrderedDict
D_sorted = dict(sorted(D.items(), key=lambda t: t[1]))

Sắp xếp theo value số (numeric sort)

D = {'a': 10, 'b': 5, 'c': 20}
dict(sorted(D.items(), key=lambda t: t[1]))  # {'b': 5, 'a': 10, 'c': 20}