Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - หาค่าร่วมของ Dictionary สองตัวจาก Key

สร้าง Dictionary ใหม่จาก Key ที่ซ้ำกันในสอง Dictionary

ตัวอย่าง:

Input: dict_1 = {'A': 1, 'B': 2, 'C': 3}
       dict_2 = {'A': 1, 'C': 4, 'D': 5}
Output: {'A': 1, 'C': 3}  # ใช้ค่าจาก dict_1

วิธีที่ 1: Dictionary Comprehension

dict_1 = {'A': 1, 'B': 2, 'C': 3}
dict_2 = {'A': 1, 'C': 4, 'D': 5}

result = {key: dict_1[key] for key in dict_1 if key in dict_2}
print(result)  # {'A': 1, 'C': 3}

วิธีที่ 2: Bitwise & Operator (เฉพาะ Key และ Value ที่ตรงกันทั้งคู่)

result = dict(dict_1.items() & dict_2.items())
print(result)  # {'A': 1}

สรุป

  • Comprehension: ใช้ค่าจาก dict_1, รองรับ Key ซ้ำ Value ไม่เหมือนกัน
  • Bitwise &: เฉพาะ Key-Value ที่เหมือนกันทุกประการ