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

เรียงลำดับคีย์และค่า (ที่เป็นลิสต์) ในดิกชันนารี Python


เมื่อต้องการเรียงลำดับดิกชันนารีทั้งตามคีย์และตามค่า (ที่เป็นลิสต์) ภายใน ใช้ sorted() ร่วมกับ Dictionary Comprehension

ตัวอย่างโค้ด

my_dict = {'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]}
print("The dictionary is:")
print(my_dict)

result = {}
for key in sorted(my_dict):
    result[key] = sorted(my_dict[key])

print("The sorted dictionary is:")
print(result)

ผลลัพธ์

The dictionary is: {'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]}
The sorted dictionary is: {'Hi': [1, 3, 6], 'Mark': [7, 16], 'there': [2, 6, 9]}

คำอธิบาย

  • sorted(my_dict) คืนลิสต์คีย์เรียงตามตัวอักษร: ['Hi', 'Mark', 'there']

  • วนลูปตามคีย์ที่เรียงแล้ว

  • สำหรับแต่ละคีย์ เรียงลิสต์ค่าด้วย sorted(my_dict[key])

  • สร้างดิกชันนารีใหม่ที่เรียงแล้วทั้งคีย์และค่า