[Python] Deep copy of a dict in python

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página