พจนานุกรม Python มีคู่คีย์และค่า ในบางสถานการณ์ เราจำเป็นต้องจัดเรียงรายการในพจนานุกรมตามคีย์ ในบทความนี้ เราจะเห็นวิธีต่างๆ ในการรับผลลัพธ์ที่เรียงลำดับจากรายการในพจนานุกรม
การใช้โมดูลตัวดำเนินการ
โมดูล Operator มีฟังก์ชัน itemgetter ซึ่งสามารถรับ 0 เป็นดัชนีของพารามิเตอร์อินพุตสำหรับคีย์ของพจนานุกรม เราใช้ฟังก์ชัน sorted ที่ด้านบนของ itemgetter และรับเอาต์พุตที่จัดเรียง
ตัวอย่าง
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
import operator
print("\nGiven dictionary", str(dict))
print ("sorted order from given dictionary")
for k, n in sorted(dict.items(),key = operator.itemgetter(0),reverse = False):
print(k, " ", n) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
12 Mon
17 Wed
21 Tue การใช้วิธีการเรียงลำดับ
วิธีการจัดเรียงสามารถใช้กับพจนานุกรมได้โดยตรง ซึ่งจะเรียงลำดับคีย์ของพจนานุกรม
ตัวอย่าง
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using sorted()
print ("Given dictionary", str(dict))
print ("sorted order from given dictionary")
for k in sorted(dict):
print (dict[k]) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
Mon
Wed
Tue การใช้ dict.items()
เราสามารถใช้วิธี sorted กับ dict.items ได้ด้วย ในกรณีนี้ สามารถพิมพ์ได้ทั้งคีย์และค่า
ตัวอย่าง
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using d.items()
print("\nGiven dictionary", str(dict))
print ("sorted order from given dictionary")
for k, i in sorted(dict.items()):
print(k,i) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
12 Mon
17 Wed
21 Tue