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

Trích xuất giá trị duy nhất từ dictionary Python

Dùng set comprehension lồng trong sorted để gom tất cả giá trị từ các list value, loại trùng và sắp xếp.

Ví dụ

my_dict = {
    'hi': [5, 3, 8, 0],
    'there': [22, 51, 63, 77],
    'how': [7, 0, 22],
    'are': [12, 11, 45],
    'you': [56, 31, 89, 90]
}
print("Dictionary:", my_dict)

unique = sorted({elem for val in my_dict.values() for elem in val})
print("Giá trị duy nhất:", unique)

Kết quả

Dictionary: {'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}
Giá trị duy nhất: [0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]

Giải thích

  • my_dict.values() lấy các list value.
  • Set comprehension {elem for val in ... for elem in val} flatten và loại trùng.
  • sorted() sắp xếp kết quả.
  • Cách viết Pythonic, một dòng, hiệu quả.