พจนานุกรมหลามสองพจนานุกรมอาจมีคีย์ทั่วไประหว่างกัน ในบทความนี้ เราจะพบวิธีหาความแตกต่างของคีย์ที่มีอยู่ในพจนานุกรมสองชุด
พร้อมชุด
ที่นี่เราใช้พจนานุกรมสองชุดและใช้ฟังก์ชัน set กับพจนานุกรมเหล่านั้น จากนั้นเราลบทั้งสองชุดเพื่อให้ได้ผลต่าง เราทำทั้งสองวิธีโดยลบพจนานุกรมที่สองออกจากแรกและถัดไปลบแบบฟอร์มพจนานุกรมแรกที่สอง คีย์ที่ไม่ธรรมดาจะแสดงอยู่ในชุดผลลัพธ์
ตัวอย่าง
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
res1 = set(dictA) - set(dictB)
res2 = set(dictB) - set(dictA)
print("\nThe difference in keys between both the dictionaries:")
print(res1,res2) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The difference in keys between both the dictionaries:
{'2', '1'} {'4', '5'} การใช้ in with for loop
ในอีกแนวทางหนึ่ง เราสามารถใช้ for loop เพื่อวนซ้ำผ่านคีย์ของพจนานุกรมหนึ่งๆ และตรวจสอบการมีอยู่โดยใช้ in clause ในพจนานุกรมที่สอง
ตัวอย่าง
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
print("\nThe keys in 1st dictionary but not in the second:")
for key in dictA.keys():
if not key in dictB:
print(key) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The keys in 1st dictionary but not in the second:
1
2