เมื่อวิเคราะห์ข้อมูลด้วย Python เราพบสถานการณ์ที่ต้องรวมสอง dictionary โดยบวกค่าขององค์ประกอบที่ key มีค่าเท่ากัน ในบทความนี้เราจะดูการรวม dictionary แบบนี้
ใช้ For loop และตัวดำเนินการ |
ในวิธีนี้เราออกแบบลูป for เพื่อตรวจสอบการมีอยู่ของค่า key ในทั้งสอง dictionary แล้วบวกกัน สุดท้ายรวมสอง dictionary ด้วยตัวดำเนินการ | ที่มีสำหรับ dictionary
ตัวอย่าง
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}
# Add with common key
for key in dictB:
if key in dictA:
dictB[key] = dictB[key] + dictA[key]
else:
pass
res = dictA | dictB
print(res)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
{'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10}
การใช้ Counter
ฟังก์ชัน Counter จากโมดูล Collections สามารถนำไปใช้รวมสอง dictionary ได้โดยตรงซึ่งเก็บ key ไว้ และบวกค่าที่ key ตรงกัน
ตัวอย่าง
from collections import Counter
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}
res = Counter(dictA) + Counter(dictB)
print(res)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
Counter({'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10})