Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีจัดเรียง Dictionary ใน Python ตาม Keys

Standard Distribution ของ Python มีโมดูล collections ซึ่งมีนิยามของ High-Performance Container Data Types OrderedDict เป็น Subclass ของ Dictionary ที่จำลำดับของ Entries ที่เพิ่มใน Dictionary Object เมื่อ Iterate Over OrderedDict Items จะถูกคืนค่าในลำดับที่ Keys ถูกเพิ่มครั้งแรก

>>> from collections import OrderedDict
>>> D = {5: 'fff', 3: 'ttt', 1: 'ooo', 4: 'bbb', 2: 'ddd'}
>>> OrderedDict(D.items())
OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])

เรายังต้องใช้ฟังก์ชัน sorted() ที่จัดเรียง Elements ใน Iterable ตามลำดับที่ระบุ ฟังก์ชันนี้รับ Function เป็น Argument ซึ่งใช้เป็น Key สำหรับการจัดเรียง เนื่องจากเราต้องการจัดเรียง Dictionary ตาม Keys เราใช้ Element ตำแหน่งที่ 0 ของ Tuple เป็น Key สำหรับการจัดเรียง

>>> 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 Object สามารถแปลงเป็น Regular Dictionary Object ได้

>>> D1 = dict(OrderedDict(sorted(D.items(), key=lambda t: t[0])))
>>> D1
{1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}