Search code examples
pythondeep-copy

Deep copy of a dict in python


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.


Solution

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