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

วิธีรวม Python Dictionary สองตัวเข้าด้วยกัน

ใน Python 3.5+ คุณสามารถใช้ออเปอเรเตอร์ ** เพื่อ unpack dictionary และรวมหลาย dictionary ได้ด้วยไวยากรณ์ดังนี้:

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'}

อีกวิธีหนึ่งคือใช้ฟังก์ชัน copy และ update เพื่อรวม dictionary ตัวอย่างเช่น:

def merge_dicts(x, y):
    z = x.copy()  # เริ่มต้นด้วย keys และ values ของ x
    z.update(y)   # แก้ไข z ด้วย keys และ values ของ y
    return z

a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)

ผลลัพธ์:

{'foo': 125, 'bar': 'hello'}