Python standard library có module collections chứa OrderedDict – subclass của dict nhớ thứ tự thêm entry. Khi iterate OrderedDict, item trả về theo thứ tự key được thêm lần đầu.
Cần dùng sorted() để sắp xếp các phần tử trong iterable theo thứ tự chỉ định. Hàm nhận key function làm tiêu chí sắp xếp. Vì muốn sắp theo key, lấy phần tử thứ 0 của tuple (key, value).
Ví dụ
>>> from collections import OrderedDict
>>> D = {5:'fff', 3:'ttt', 1:'ooo', 4:'bbb', 2:'ddd'}
>>> OrderedDict(sorted(D.items(), key=lambda t: t[0]))
OrderedDict([(1, 'ooo'), (2, 'ddd'), (3, 'ttt'), (4, 'bbb'), (5, 'fff')])
OrderedDict có thể chuyển về dict thường:
>>> D1 = dict(OrderedDict(sorted(D.items(), key=lambda t: t[0])))
>>> D1
{1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}
Từ Python 3.7+: dict thường đã giữ insertion order. Chỉ cần: dict(sorted(D.items())) (mặc định sort theo key). Không cần OrderedDict trừ khi cần method đặc thù như move_to_end.