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

ดึงรายการจากพจนานุกรมในลำดับที่เรียงแล้วใน Python

พจนานุกรมของ Python มีคู่คีย์และค่า ในบางสถานการณ์เราต้องการรายการของพจนานุกรมให้เรียงตามคีย์ ในบทความนี้เราจะมาดูวิธีต่างๆ ในการได้ผลลัพธ์ที่เรียงแล้วจากรายการในพจนานุกรม

ใช้โมดูล Operator

โมดูล 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

ใช้เมธอด Sorted

เมธอด sorted สามารถนำไปใช้กับพจนานุกรมโดยตรงซึ่งจะเรียงคีย์ของพจนานุกรม

ตัวอย่าง

dict = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
# ใช้ 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'}
# ใช้ 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