Python 字典的浅拷贝与深拷贝
最近在写 Python 脚本的时候用到了字典的拷贝,踩了一个坑,在此记录一下
对于 Python 字典,如果直接用=
赋值,修改一个字典会同时修改另一个:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dict_1 = {'1': 1}
>>> dict_2 = dict_1
>>> dict_2['1'] = 2
>>> dict_2
{'1': 2}
>>> dict_1
{'1': 2}
一般使用copy()
方法进行拷贝,在修改拷贝后的字典时,不会影响原来的字典:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dict_1 = {'1': 1}
>>> dict_2 = dict_1.copy()
>>> dict_2['1'] = 2
>>> dict_2
{'1': 2}
>>> dict_1
{'1': 1}
但是,当字典超过一层时,修改copy()
后的键值时会同样修改原字典的键值:
>>> dict_3 = {'1': {'1': 3}}
>>> dict_4 = dict_3.copy()
>>> dict_4['1']['1'] = 4
>>> dict_4
{'1': {'1': 4}}
>>> dict_3
{'1': {'1': 4}}
后来网上查了一下才知道,Python 字典的拷贝分为浅拷贝和深拷贝
copy()
为浅拷贝,只拷贝字典的父级目录;而deepcopy()
为深拷贝,会将整个字典全都拷贝
使用deepcopy()
需要导入copy
模块
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> dict_3 = {'1': {'1': 3}}
>>> dict_4 = copy.deepcopy(dict_3)
>>> dict_4['1']['1'] = 4
>>> dict_4
{'1': {'1': 4}}
>>> dict_3
{'1': {'1': 3}}