Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Sắp xếp list Dictionary theo giá trị tại chỉ số i của Key

Khi cần sắp xếp list dictionary dựa trên ký tự tại vị trí i của giá trị thuộc key K, ta dùng sorted() và lambda.

Ví dụ

my_list = [
    {"Python": "Best", "to": "Code"},
    {"Python": "Good", "to": "Learn"},
    {"Python": "object", "to": "cool"},
    {"Python": "oriented", "to": "language"}
]

print("Danh sách là:")
print(my_list)

K = "Python"
print("Key K:", K)
i = 2
print("Chỉ số i:", i)

my_result = sorted(my_list, key=lambda sub: sub[K][i])

print("Danh sách kết quả:")
print(my_result)

Kết quả đầu ra

Danh sách là:
[{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'oriented', 'to': 'language'}]
Key K: Python
Chỉ số i: 2
Danh sách kết quả:
[{'Python': 'oriented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'Best', 'to': 'Code'}]

Giải thích

  • Key K = "Python", i = 2 (ký tự thứ 3, 0-based).
  • Giá trị tại K[2]: "Best"[2]='s', "Good"[2]='o', "object"[2]='j', "oriented"[2]='r'.
  • Sắp xếp theo ký tự: 'j'(object) < 'o'(Good) < 'r'(oriented) < 's'(Best).
  • Kết quả: oriented, object, Good, Best.

Lưu ý: Nếu chuỗi ngắn hơn i+1, sẽ lỗi IndexError. Cần xử lý: sub[K][i] if len(sub[K]) > i else ''.