1. 使用 update() 方法,第二个参数合并第一个参数
示例代码:
dic1 = {
"A": "a",
"B": "b",
"C": "c"
}
dic2 = {
"X": "x",
"Y": "y",
"Z": "z"
}
print(dic1)
print(dic2)
print("*" * 100)
# 使用 update() 方法,第二个参数合并第一个参数
dic3 = dic1.update(dic2)
print(dic3)
print(dic1)
print(dic2)
运行效果:
2. 使用 **,函数将参数以字典的形式导入
示例代码:
dic1 = {
"A": "a",
"B": "b",
"C": "c"
}
dic2 = {
"X": "x",
"Y": "y",
"Z": "z"
}
print(dic1)
print(dic2)
print("*" * 100)
# 使用 **,函数将参数以字典的形式导入
dic4 = {**dic1, **dic2}
print(dic4)
print(dic1)
print(dic2)
运行效果:
3. 常规方法处理 【不建议这样使用】
示例代码:
dic1 = {
"A": "a",
"B": "b",
"C": "c"
}
dic2 = {
"X": "x",
"Y": "y",
"Z": "z"
}
print(dic1)
print(dic2)
print("*" * 100)
dic3 = {}
for i, j in dic1.items():
dic3[i] = j
for k, m in dic2.items():
dic3[k] = m
print(dic3)
print(dic1)
print(dic2)
运行效果:
4. 借助dict(d1.items(),d2.items()) 【适用于python2,不再适用于python3】
示例代码:
dic1 = {
"A": "a",
"B": "b",
"C": "c"
}
dic2 = {
"X": "x",
"Y": "y",
"Z": "z"
}
print(dic1)
print(dic2)
print("*" * 100)
print(dic2.items())
# 借助dict(d1.items(),d2.items())
dic3 = dict(dic1.items() + dic2.items())
print(dic3)
print(dic1)
print(dic2)
运行效果:
目前这种方法适合用于python2,但在python3中已经不能使用。
5. 使用“|”运算符 【适用于python2,不再适用于python3】
示例代码:
dic1 = {
"A": "a",
"B": "b",
"C": "c"
}
dic2 = {
"X": "x",
"Y": "y",
"Z": "z"
}
print(dic1)
print(dic2)
print("*" * 100)
print(dic2.items())
# 直接使用“|”
dic3 = dic1 | dic2
print(dic3)
print(dic1)
print(dic2)
运行效果:
目前这种方法适合用于python2,但在python3中已经不能使用。