Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Gộp hai Python dictionary

Python 3.5+: dùng unpacking **.

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

Version cũ: c = dict(a, **b).

Cách khác: copy() + update().

def merge_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z