Python中的字典合并

方式1

x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}

z1 = {**x, **y}
print(z1)   # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

方式2

x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}

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

z2 = merge(x, y)
print(z2)    # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

多个字典合并

x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {'e': 5, 'f': 6}

def merge_dicts(*dict_args):
    result = {}
    for item in dict_args:
        result.update(item)
    return result

z3 = merge_dicts(x,y,z)
print(z3) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
posted @ 2020-08-18 10:39  KadyCui  阅读(306)  评论(0编辑  收藏  举报