Python 3.7+ Dictionary รักษาลำดับ insertion order แล้ว แต่การเรียงตาม Value ต้องใช้ sorted() ร่วมกับ collections.OrderedDict (หรือ dict ธรรมดาใน 3.7+)
ตัวอย่างข้อมูล
>> D = {5: 'fff', 3: 'ttt', 1: 'ooo', 4: 'bbb', 2: 'ddd'}
วิธีที่ 1: OrderedDict + sorted (Python ทุกเวอร์ชัน)
>> from collections import OrderedDict >>> OrderedDict(sorted(D.items(), key=lambda t: t[1])) OrderedDict([(4, 'bbb'), (2, 'ddd'), (5, 'fff'), (1, 'ooo'), (3, 'ttt')])
วิธีที่ 2: dict() + sorted (Python 3.7+, รักษาลำดับ)
>> dict(sorted(D.items(), key=lambda t: t[1]))
{4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}
คำอธิบาย
D.items()→ iterable ของ (key, value) tuplessorted(..., key=lambda t: t[1])เรียงตาม index 1 (value)lambda t: t[1]ฟังก์ชันดึง value จาก tuple (key, value)
เรียงจากมากไปน้อย (Reverse)
>> dict(sorted(D.items(), key=lambda t: t[1], reverse=True))
{3: 'ttt', 1: 'ooo', 5: 'fff', 2: 'ddd', 4: 'bbb'}
เรียงตาม Key (แทน Value)
>> dict(sorted(D.items(), key=lambda t: t[0]))
{1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}