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

Sắp xếp key và value list trong dictionary Python

Duyệt qua các key đã sắp xếp, sắp xếp lại list value tương ứng, xây dictionary mới.

Ví dụ

my_dict = {
    'Hi': [1, 6, 3],
    'there': [2, 9, 6],
    'Mark': [16, 7]
}
print("Dictionary gốc:", my_dict)

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

print("Dictionary đã sắp xếp:", result)

Kết quả

Dictionary gốc: {'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]}
Dictionary đã sắp xếp: {'Hi': [1, 3, 6], 'Mark': [7, 16], 'there': [2, 6, 9]}

Giải thích

  • sorted(my_dict) trả về list key theo thứ tự alphabe.
  • Với mỗi key, sắp xếp list value: sorted(my_dict[key]).
  • Gán vào dictionary mới result.
  • Kết quả: key tăng dần, mỗi value list cũng tăng dần.