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() với key function trên dict.items(), kết hợp collections.OrderedDict (hoặc dict thường Python 3.7+ giữ thứ tự).

Ví dụ

from collections import OrderedDict

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

# Sắp xếp theo value (t[1] là value trong tuple (k, v))
sorted_items = sorted(D.items(), key=lambda t: t[1])
# [('4', 'bbb'), ('2', 'ddd'), ('5', 'fff'), ('1', 'ooo'), ('3', 'ttt')]

# Tạo OrderedDict (giữ thứ tự)
od = OrderedDict(sorted_items)

# Hoặc dict thường (Python 3.7+ giữ insertion order)
D1 = dict(sorted_items)
print(D1)  # {4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}

Sắp xếp giảm dần

sorted(D.items(), key=lambda t: t[1], reverse=True)

Sắp xếp theo key

sorted(D.items(), key=lambda t: t[0])