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

Python – Lấy giá trị duy nhất từ danh sách Dictionary

Khi cần lấy tất cả giá trị duy nhất (unique values) từ danh sách các dictionary, ta dùng set và list comprehension.

Ví dụ

my_dictionary = [
    {'Python': 11, 'is': 22},
    {'fun': 11, 'to': 33},
    {'learn': 22},
    {'object': 9},
    {'oriented': 11}
]

print("Danh sách dictionary:")
print(my_dictionary)

my_result = list(set(value for element in my_dictionary for value in element.values()))

print("Danh sách giá trị duy nhất:")
print(my_result)

print("Sau khi sắp xếp:")
my_result.sort()
print(my_result)

Kết quả đầu ra

Danh sách dictionary:
[{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}]
Danh sách giá trị duy nhất:
[33, 11, 22, 9]
Sau khi sắp xếp:
[9, 11, 22, 33]

Giải thích

  • Generator expression: value for element in my_dictionary for value in element.values() lấy tất cả values từ tất cả dict.
  • set(...) loại bỏ trùng lặp.
  • list(...) chuyển về list.
  • sort() sắp xếp tăng dần.

Cách khác: set().union(*[d.values() for d in my_dictionary]).