Dùng sorted(dict.items(), key=lambda kv: kv[0]) sắp xếp theo key.
Ví dụ
from collections import OrderedDict
D = {5: 'fff', 3: 'ttt', 1: 'ooo', 4: 'bbb', 2: 'ddd'}
# Tăng dần theo key
D_sorted = dict(sorted(D.items(), key=lambda t: t[0]))
print(D_sorted) # {1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}
# Giảm dần
D_desc = dict(sorted(D.items(), key=lambda t: t[0], reverse=True))
Lưu ý
- Python 3.7+:
dictgiữ insertion order →dict(sorted(...))đủ. - Python <3.7: dùng
OrderedDict(sorted(...)). - Key phải comparable (cùng kiểu hoặc hỗ trợ so sánh).