Sử dụng sorted() và list comprehension để lọc ra các dictionary trong danh sách mà các giá trị (values) của nó đã được sắp xếp tăng dần theo thứ tự chèn (insertion order).
Ví dụ
Minh họa:
my_list = [{'python': 2, 'is': 8, 'fun': 10}, {'python': 1, 'for': 10, 'coding': 9}, {'cool': 3, 'python': 4}]
print("Danh sách:", my_list)
my_result = [index for index in my_list if sorted(list(index.values())) == list(index.values())]
print("Dictionary có giá trị tăng dần:", my_result)
Kết quả
Danh sách: [{'python': 2, 'fun': 10, 'is': 8}, {'python': 1, 'coding': 9, 'for': 10}, {'python': 4, 'cool': 3}]
Dictionary có giá trị tăng dần: [{'python': 1, 'coding': 9, 'for': 10}]
Giải thích
- Duyệt từng dictionary trong list.
- Chuyển values thành list, so sánh với phiên bản sorted của nó.
- Nếu giống nhau -> values đã tăng dần theo thứ tự chèn.