【重点】
dic = dic1.copy(),是浅拷贝;
dic = dict(dict1),是深拷贝;
尽量用dict(d1, **d2)进行合并,是深拷贝;
注意:以上基于python3.6版本,python2.7请绕行。
=============================================
python中的双层字典合并,即字典的value也是一个字典。
如果采用简单的update()方法,如d3=d1.copy(); d3.update(d2),在相同关键词情况下,会使得d2中的value会覆盖d1中的value;
如果采用d3=update(d1, **d2),仍然会因为覆盖而得到错误结果。
下面提两种改进的解决方案,定义两个字典(定义参考这里)
dict1 = {"小明": {"name":"owen", "age": 18 }}
dict2 = {"小明": {"birthday": "1999-11-22", "height": 180 }}
合并两个字典应该得到:
{ “小明”: {"name":"owen", "age": 18, "birthday": "1999-11-22", "height": 180 }}
方法1:借助字典的update()方法,注意这里要用到深拷贝
from copy import deepcopy
dict1 = {"小明": {"name":"owen", "age": 180 }}
dict2 = {"小明": {"birthday": "1999-11-22", "height": 180 }}
dic = deepcopy(dict1)
print(dict1)
for key in dict2.keys():
if key in dic:
dic[key].update(dict2[key])
else:
dic[key] = dict2[key]
print(dic)
# {'小明': {'name': 'owen', 'age': 18, 'birthday': '1999-11-22', 'height': 180}}
print(dict1)
# {'小明': {'name': 'owen', 'age': 180}}
方法2:借助字典的dict(d1, **d2)方法
dict1 = {"小明": {"name":"owen", "age": 180 }}
dict2 = {"小明": {"birthday": "1999-11-22", "height": 180 }}
dic = dict(dict1, **dict2) # 合并两个字典,如果有相同关键字,以dict2的value填充
for key in dic.keys(): # 找回dict1中关键字对应的value
if key in dict1:
dic[key] = dict(dic[key], **dict1[key])
print(dic)
# {'小明': {'birthday': '1999-11-22', 'height': 180, 'name': 'owen', 'age': 180}}
print(dict1)
# {'小明': {'name': 'owen', 'age': 180}}
方法 2 等同于:
dictMerged2 = deepcopy(dict1)
dictMerged2.update( dict2 )
或者
dictMerged2 = dict( dict1 )
dictMerged2.update( dict2 )
--------------------------------------------------------------------------
【有坑】
如果我用dic=dict1.copy()来给函数赋值,实际上是一层浅拷贝:dic和dict仍然用着相同的元素地址。
浅拷贝在value值为数字、字符串、元祖等不可变元素时,和深拷贝没什么区别;
但是,当value是字典、列表等可变元素时,改变dic的值,dict1的值也会随之改变。
from copy import deepcopy
dict1 = {"小明": {"name":"owen", "age": 180 }}
dict2 = {"小明": {"birthday": "1999-11-22", "height": 180 }}
dic = dict1.copy()
print(dict1)
for key in dict2.keys():
if key in dic:
dic[key].update(dict2[key])
else:
dic[key] = dict2[key]
print(dic)
print(dict1)
# {'小明': {'name': 'owen', 'age': 180}}
# {'小明': {'name': 'owen', 'age': 180, 'birthday': '1999-11-22', 'height': 180}}
# {'小明': {'name': 'owen', 'age': 180, 'birthday': '1999-11-22', 'height': 180}}
但是用方法2,则不会存在这层担忧:
dict1 = {"小明": {"name":"owen", "age": 180 }}
dict2 = {"小明": {"birthday": "1999-11-22", "height": 180 }}
dic = dict(dict1, **dict2) # 合并两个字典,如果有相同关键字,以dict2的value填充
print(dict1)
for key in dic.keys(): # 找回dict1中关键字对应的value
if key in dict1:
dic[key] = dict(dic[key], **dict1[key])
print(dic)
print(dict1)
# {'小明': {'name': 'owen', 'age': 180}}
# {'小明': {'birthday': '1999-11-22', 'height': 180, 'name': 'owen', 'age': 180}}
# {'小明': {'name': 'owen', 'age': 180}}