การเรียงลำดับ Dictionary ใน Python
Dictionary ประกอบด้วย Key-Value Pairs สามารถเรียงได้ 2 แบบ:
- Sort by Key: เรียงตาม Key เรียงน้อยไปมาก (Value ไม่สนใจ)
- Sort by Value: เรียงตาม Value เรียงน้อยไปมาก
วิธีที่ 1: เรียงตาม Key
Input/Output
Input: {2:90, 1:100, 8:3, 5:67, 3:5}
Output: {1:100, 2:90, 3:5, 5:67, 8:3}
โค้ด
dic = {2:90, 1:100, 8:3, 5:67, 3:5}
dic2 = {}
for i in sorted(dic): # sorted(dic) = [1, 2, 3, 5, 8] (Keys เรียงแล้ว)
dic2[i] = dic[i]
print(dic2)
ผลลัพธ์
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
คำอธิบายบรรทัดต่อบรรทัด
- ประกาศ Dictionary ที่ต้องการเรียง
- ประกาศ Dictionary ว่างสำหรับผลลัพธ์
sorted(dic)คืน List ของ Keys ที่เรียงแล้ว (ไม่รวม Values)- Loop ผ่าน Keys ที่เรียงแล้ว ใส่ Key-Value ลง Dictionary ใหม่
- dic2 มี Key-Value Pairs เรียงตาม Key แล้ว
วิธีสั้น (Python 3.7+ Dictionary 保持 Insertion Order)
# Dictionary Comprehension
dic2 = {k: dic[k] for k in sorted(dic)}
print(dic2)
# หรือใช้ dict() กับ sorted items
dic2 = dict(sorted(dic.items()))
print(dic2)
วิธีที่ 2: เรียงตาม Value
Input/Output
Input: {2:90, 1:100, 8:3, 5:67, 3:5}
Output: {8:3, 3:5, 5:67, 2:90, 1:100}
โค้ด
dic = {2:90, 1:100, 8:3, 5:67, 3:5}
# sorted(dic.items(), key=lambda x: x[1]) เรียง Items ตาม Value (Index 1)
# dict() แปลงกลับเป็น Dictionary
dic2 = dict(sorted(dic.items(), key=lambda x: x[1]))
print(dic2)
ผลลัพธ์
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
คำอธิบาย
dic.items()คืน View ของ (Key, Value) Pairskey=lambda x: x[1]ใช้ Lambda Function ระบุว่า เรียงตาม Element Index 1 (Value)sorted(...)คืน List ของ Tuples เรียงแล้วdict(...)แปลงกลับเป็น Dictionary
การเรียงแบบ Descending (มากไปน้อย)
# เรียง Key มากไปน้อย
desc_key = dict(sorted(dic.items(), key=lambda x: x[0], reverse=True))
print(desc_key) # {8: 3, 5: 67, 3: 5, 2: 90, 1: 100}
# เรียง Value มากไปน้อย
desc_val = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
print(desc_val) # {1: 100, 2: 90, 5: 67, 3: 5, 8: 3}
Python 3.7+ Guarantee
ตั้งแต่ Python 3.7 Dictionary รักษา Insertion Order ไว้ (Officially guaranteed จาก 3.8+) ดังนั้น Dictionary ที่สร้างจาก Sorted Items จะเรียงตามที่ต้องการ
Operator.itemgetter Alternative
from operator import itemgetter
# เรียงตาม Value
dic2 = dict(sorted(dic.items(), key=itemgetter(1)))
# itemgetter(1) เร็วกว่า lambda เล็กน้อย