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

Python – เรียงลำดับ Dictionary ตามขนาด (Size)


เมื่อต้องการเรียงลำดับ dictionary ตามขนาด ใช้เมธอดที่รับพารามิเตอร์หนึ่ง ใช้ 'len' เพื่อหาผลลัพธ์

สาธิตด้านล่าง:

ตัวอย่าง

def get_len(element): 
    return len(element) 
my_dict = [{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}] 
print("The dictionary is :") 
print(my_dict) 
my_dict.sort(key=get_len) 
print("The result is :") 
print(my_dict)

ผลลัพธ์

The dictionary is : [{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}] 
The result is : [{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]

คำอธิบาย

  • กำหนดเมธอด 'get_len' รับ element คืนค่าความยาว
  • กำหนดลิสต์ของ dictionary และแสดงผล
  • เรียงลิสต์ dictionary ด้วย key เป็นเมธอดที่กำหนด
  • แสดงผลลัพธ์บนคอนโซล