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

Tìm sự khác biệt key giữa hai Dictionary Python (symmetric difference)

Dùng set trên dict.keys() và phép symmetric difference ^ (hoặc .symmetric_difference()) để lấy key chỉ xuất hiện ở một trong hai dict.

Ví dụ

D1 = {1: 100, 2: 200, 3: 300}
D2 = {1: 1000, 3: 300, 5: 500}

diff_keys = set(D1.keys()) ^ set(D2.keys())
print(diff_keys)  # {2, 5}

Các phép toán set hữu ích khác

set(D1) & set(D2)   # intersection: key chung → {1, 3}
set(D1) | set(D2)   # union: tất cả key → {1, 2, 3, 5}
set(D1) - set(D2)   # difference: key chỉ có ở D1 → {2}

Lưu ý: set(D1) tương đương set(D1.keys()).