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

Python - กรอง Dictionary ที่ Value เรียงจากน้อยไปมาก

กรอง Dictionary ในลิสต์ ที่มี Value เรียงลำดับจากน้อยไปมาก (Ascending) โดยใช้ List Comprehension และ sorted()

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

my_list = [{'python': 2, 'is': 8, 'fun': 10}, {'python': 1, 'for': 10, 'coding': 9}, {'cool': 3, 'python': 4}]
print("The list is :")
print(my_list)

my_result = [index for index in my_list if sorted(list(index.values())) == list(index.values())]
print("The resultant dictionary is :")
print(my_result)

ผลลัพธ์

The list is : [{'python': 2, 'fun': 10, 'is': 8}, {'python': 1, 'coding': 9, 'for': 10}, {'python': 4, 'cool': 3}]
The resultant dictionary is : [{'python': 1, 'coding': 9, 'for': 10}]

คำอธิบาย

  • list(index.values()) ดึงค่า Value ของ Dictionary
  • sorted(...) เรียงค่า Value จากน้อยไปมาก
  • เปรียบเทียบว่าเรียงแล้วเท่ากับลำดับเดิมหรือไม่
  • Dictionary ใน Python 3.7+ คงลำดับ Insertion Order