ใน Python 3.5+ คุณสามารถใช้โอเปอเรเตอร์ ** เพื่อแกะพจนานุกรมและรวมพจนานุกรมหลาย ๆ พจนานุกรมโดยใช้ไวยากรณ์ต่อไปนี้:
a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c) สิ่งนี้จะให้ผลลัพธ์:
{'foo': 125, 'bar': 'hello'} ไม่รองรับในเวอร์ชันเก่า อย่างไรก็ตาม คุณสามารถแทนที่ได้โดยใช้รูปแบบที่คล้ายกันต่อไปนี้:
a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c) สิ่งนี้จะให้ผลลัพธ์:
{'foo': 125, 'bar': 'hello'} สิ่งที่คุณทำได้อีกอย่างคือการใช้ฟังก์ชันคัดลอกและอัปเดตเพื่อรวมพจนานุกรม ตัวอย่างเช่น
def merge_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modify z with y's keys and values
return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c) สิ่งนี้จะให้ผลลัพธ์:
{'foo': 125, 'bar': 'hello'}