python中dict的深拷贝

python中dict的深拷贝

本文介绍了python中dict的深拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

>>>my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}>>>my_copy = my_dict.deepcopy()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'dict' 对象没有属性 'deepcopy'>>>my_copy = my_dict.copy()>>>my_dict['a'][2] = 7>>>my_copy['a'][2]7

最后一行应该是3.

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

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

解决方案

怎么样:

导入副本d = { ... }d2 = copy.deepcopy(d)

Python 2 或 3:

Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 位 (AMD64)] on win32输入帮助"、版权"、信用"或许可"以获取更多信息.>>>导入副本>>>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>>>

I would like to make a deep copy of a dict in python. Unfortunately the .deepcopy() method doesn't exist for the dict. How do I do that?

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

The last line should be 3.

I would like that modifications in my_dict don't impact the snapshot my_copy.

How do I do that? The solution should be compatible with Python 3.x.

解决方案

How about:

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

Python 2 or 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
>>>

这篇关于python中dict的深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:30