(1)字典直接赋值给变量
#!/usr/bin/env python3 dct = {"key1":"小白","key2":"小黑"} dct_1 = dct dct_1['key2'] = "小灰" print(dct) # {'key1': '小白', 'key2': '小灰'}
你会发现这种赋值方式,dct_1改变后,dct也跟着改变。这是因为字典赋值是引用性赋值,赋的是地址。
(2)dict.copy() 对象拷贝,浅拷贝
#!/usr/bin/env python3 dct = {'key1':'小白','key2':['小黑']} dct_1 = dct.copy() dct_1['key1'] = '小灰' print(dct) # {'key1': '小白', 'key2': '小黑'} dct_1['key2'].append('小红') print(dct) #{'key1': '小白', 'key2': ['小黑', '小红']}
copy虽然修改key1不会影响原数据(返过来也一样),但是修改key2会影响。因为key2的值仍然是地址(列表赋值也是引用赋值)。
(3)deepcopy(dict) 对象拷贝,深拷贝
#!/usr/bin/env python3 import copy dct = {'key1':'小白','key2':['小黑']} dct_1 = copy.deepcopy(dct) dct_1['key1'] = '小灰' print(dct) # {'key1': '小白', 'key2': '小黑'} dct_1['key2'].append('小红') print(dct) #{'key1': '小白', 'key2': ['小黑']}
深拷贝,无论你怎么修改,都不会相互影响。使用时请根据需求注意选择合适的方法