python - 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 兼容。

最佳答案

怎么样:

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
>>>

https://stackoverflow.com/questions/5105517/

相关文章:

python - 如何将本地时间字符串转换为 UTC?

python - 动态打印一行

python - pandas:使用运算符链接过滤 DataFrame 的行

python - python中的链式调用父初始化器

python - 漂亮地打印一个没有科学记数法和给定精度的 NumPy 数组

python - 如何使用 Python 重命名文件

python - 为什么访问全局变量不需要 'global' 关键字?

python - 在 Python 中将 datetime.date 转换为 UTC 时间戳

python - 在 Python 中打印多个参数

python - 为什么使用 argparse 而不是 optparse?