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

Sắp xếp dictionary Python theo key hoặc value

Sử dụng sorted() trên dictionary để sắp xếp theo key (mặc định) hoặc theo value (dùng key function).

Ví dụ

def demo_sort():
    d = {}
    d[2] = 56
    d[1] = 2
    d[5] = 12
    d[4] = 24
    d[6] = 18
    d[3] = 323

    print("Sắp xếp theo key:")
    for k in sorted(d):
        print(k, d[k])

    print("\nSắp xếp theo value:")
    for k in sorted(d, key=d.get):
        print(k, d[k])

demo_sort()

Kết quả

Sắp xếp theo key:
1 2
2 56
3 323
4 24
5 12
6 18

Sắp xếp theo value:
1 2
5 12
4 24
6 18
2 56
3 323

Giải thích

  • sorted(d) sắp xếp key.
  • sorted(d, key=d.get) sắp xếp key dựa trên value tương ứng.
  • Để sắp xếp giảm dần: thêm reverse=True.
  • Kết quả là list key đã sắp xếp, dùng để truy xuất value.