3种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
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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}