python中dict的深拷贝
·
回答问题
我想在 python 中制作一个dict的深层副本。不幸的是,dict不存在.deepcopy()方法。我怎么做?
>>> 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 兼容。
Answers
怎么样:
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
>>>
更多推荐

所有评论(0)