小编典典

python中dict的深拷贝

all

我想dict在 python 中制作 a 的深层副本。不幸的是,该.deepcopy()方法不存在于dict. 我怎么做?

>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = my_dict.deepcopy()
Traceback (most recent calll last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'deepcopy'
>>> my_copy = my_dict.copy()
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
7

最后一行应该是3.

我希望修改my_dict不会影响快照my_copy

我怎么做?该解决方案应与 Python 3.x 兼容。


阅读 139

收藏
2022-03-14

共1个答案

小编典典

怎么样:

import copy
d = { ... }
d2 = copy.deepcopy(d)

Python 2 或 3:

Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = copy.deepcopy(my_dict)
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
3
>>>
2022-03-14