คุณสามารถทำได้โดยการรวมพจนานุกรมอื่นเข้ากับพจนานุกรมแรก ใน 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'}