Python中的字典合并

2021-06-12 01:03

阅读:665

标签:字典   多个   lang   ict   pre   class   copy   item   合并   

方式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}

Python中的字典合并

标签:字典   多个   lang   ict   pre   class   copy   item   合并   

原文地址:https://www.cnblogs.com/kadycui/p/13522079.html


评论


亲,登录后才可以留言!