Python中的字典合并
2021-06-12 01:03
标签:字典 多个 lang ict pre class copy item 合并 方式1 方式2 多个字典合并 Python中的字典合并 标签:字典 多个 lang ict pre class copy item 合并 原文地址:https://www.cnblogs.com/kadycui/p/13522079.htmlx = {‘a‘: 1, ‘b‘: 2}
y = {‘c‘: 3, ‘d‘: 4}
z1 = {**x, **y}
print(z1) # {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}
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常用模块/函数