Built with Tutify.io

    AIStudyLabs

    Copy the Dictionary and edit it in Python

    Copy the Dictionary and edit it in Python

    How to deep copy the dictionary and edit it in Python without modifying the original dict? Python does not implicitly copy objects, and if you are not careful, you may end up modifying the original dictionary. In this article, we will learn how to copy a dictionary in Python, and how to edit the copy without affecting the original.

    When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state. This is why you need a deep copy of the original dictionary.

    See this example, when we edit the first dict, the other dict also changes.

    
    # The Problem with Editing a Dict
    my_dict = {'a': 1, 'b': 2}
    
    # Assign the orignal dict to new dict
    new_dict = my_dict
    
    # Edit the new Dict
    new_dict['a']=4
    
    # The other dict will also be edited
    print('Original :', my_dict)
    print('Copied :', new_dict)
    
    # Output:
    # Original dictionary: {'a': 4, 'b': 2}
    # Copied dictionary: {'a': 4, 'b': 2}
    

    In this article, we will solve this problem using the shallow copy and deep copy methods. So let's get started:

    <a id="h-1-quick-examples-to-copy-dictionary-and-edit-it"></a>

    1. Quick Examples to Copy Dictionary and Edit it

    These are just quick examples of how to copy the dictionary and edit it in Python. We will discuss each of these methods in much detail later on.

    
    # Quick Examples to Copy Dictionary and Edit it
    
    # Original Dictionary
    original_dict = {'a': 1, 'b': 2}
    
    # Method 1 : Copy Dictionary using dict() function
    new_dict = dict(original_dict)
    new_dict['a'] = 3
    
    # Method 2 : Copy Dictionary using dict.copy() method
    mutated_dict = original_dict.copy()
    mutated_dict['a'] = 4
    
    # Method 3 : Deep copy Dictionary using deepcopy() function
    import copy
    deep_copied_dict = copy.deepcopy(original_dict)
    deep_copied_dict['a'] = 5
    
    # Method 4 : Copy Dictionary using ** unpackaging
    unpacked_dict = {**original_dict}
    unpacked_dict['a'] = 6
    

    <a id="h-2-dict-copy-the-dictionary-and-edit-it"></a>

    2. dict() - Copy the Dictionary and Edit it

    To avoid spreading the change to other dictionary references, we need to create a new dictionary from the original dictionary. We can use the dict() function to create a new dictionary that is a copy of an existing dictionary, by passing the existing dictionary as an argument to the dict() constructor.

    The dict() constructor in Python can be used to create a new dictionary from an iterable of key-value pairs, or from a sequence of key-value tuples. When you pass a dictionary to the dict() constructor, a new dictionary object is created with the same key-value pairs as the original.

    
    # Copy Dict using the dict() function
    my_dict_1 = {'a': 1, 'b': 2}
    
    # Copy my_dict_1 to my_dict_2 
    my_dict_2 = dict(my_dict_1)
    
    # Edit any of the dict
    my_dict_2['a']=4
    
    # Print the original and copied dictionaries
    print('Original :', my_dict_1)
    print('Copied :', my_dict_2)
    

    This example yields the below output.

    
    # Ouput:
    Original : {'a': 1, 'b': 2}
    Copied : {'a': 4, 'b': 2}
    

    In the above example, you see that the dict() function created another instance of the dictionary. Now if we edit any of the dictionaries, the other one will not be affected.

    <a id="h-3-dict-copy-copy-original-dictionary-and-mutate-it"></a>

    3. dict.copy() - Copy Original Dictionary and Mutate it

    The copy() method of dictionaries in Python creates a shallow copy of the original dictionary. This means that a new dictionary object is created with the same key-value pairs as the original dictionary.

    
    # Create a dictionary with keys 'a' and 'b' and values 1 and 2
    original_dict = {'a': 1, 'b': 2}
    
    # Copy the original dictionary
    copied_dict = original_dict.copy()
    
    # Modify the copied dictionary by changing the value of key 'a'
    copied_dict['a'] = 3
    
    # Print both dictionaries to see the differences
    print('Original dictionary:', original_dict)
    print('Copied dictionary:', copied_dict)
    

    This example yields the below output.

    
    # Output:
    Original dictionary: {'a': 1, 'b': 2}
    Copied dictionary: {'a': 3, 'b': 2}
    

    A shallow copy is a type of copy where a new object is created and the original object's values are copied into the new object. However, it does not duplicate individual elements. Instead, the new object contains references to the original object's elements.

    See this example to clear your doubt between the normal copy and the shallow copy using the dict.copy() function.

    
    # Create the original dictionary
    original_dict = {'a': 1, 'b': [2, 3, 4]}
    
    # Create a shallow copy of the dictionary
    copied_dict = original_dict.copy()
    
    # Modify the list inside the copied dictionary
    copied_dict['b'].append(5)
    
    # Print both dictionaries and their IDs
    print("Original:", original_dict)
    print("Copied:", copied_dict)
    print("Original ID:", id(original_dict))
    print("Copied ID:", id(copied_dict))
    print("Original 'b' ID:", id(original_dict['b']))
    print("Copied 'b' ID:", id(copied_dict['b']))
    

    Yields below output.

    
    # Output:
    Original: {'a': 1, 'b': [2, 3, 4, 5]}
    Copied: {'a': 1, 'b': [2, 3, 4, 5]}
    Original ID: 1326843015936
    Copied ID: 1326841630400
    Original 'b' ID: 1326843246592
    Copied 'b' ID: 1326843246592
    

    <a id="h-4-deepcopy-deep-copy-the-dictionary-and-edit-it"></a>

    4. deepcopy() - Deep Copy the Dictionary and Edit it

    In Python, deepcopy() is a method from the copy module that creates a new object that is a deep copy of the original object. A deep copy means that all nested objects, such as lists and dictionaries, are also copied and new objects are created for them. This ensures that any changes made to the copied object do not affect the original object.

    
    # Import copy module
    import copy
    
    # create the original dictionary
    original_dict = {'a': 1, 'b': {'c': 2}}
    
    # create a deep copy of the dictionary
    copied_dict = copy.deepcopy(original_dict)
    
    # modify the value of 'c' inside the copied dictionary
    copied_dict['b']['c'] = 3
    
    # print both dictionaries and their IDs
    print("Original :", original_dict)
    print("Copied :", copied_dict)
    print("Original  ID:", id(original_dict))
    print("Copied  ID:", id(copied_dict))
    print("Original  'b' ID:", id(original_dict['b']))
    print("Copied  'b' ID:", id(copied_dict['b']))
    

    Yields the below output:

    
    # Output:
    Original : {'a': 1, 'b': {'c': 2}}
    Copied : {'a': 1, 'b': {'c': 3}}
    Original  ID: 2175881612992
    Copied  ID: 2175883228672
    Original  'b' ID: 2175882998528
    Copied  'b' ID: 2175883228608
    

    See the difference between the shallow copy and deep copy in Python.

    | Description | Shallow Copy (copy()) | Deep Copy (deepcopy()) | | --- | --- | --- | | Copies top-level dictionary | Yes | Yes | | Creates new dictionary object | Yes | Yes | | Copies nested objects | References | New objects | | Modifications to nested objects affect the original | Yes | No |

    <a id="h-5-copy-dict-using-unpackaging"></a>

    5. Copy Dict using ** unpackaging

    In Python, we can also copy a dictionary using the ** unpacking operator. This method creates a new dictionary and unpacks the key-value pairs of the original dictionary into the new dictionary. This is a concise and straightforward way of copying a dictionary.

    Here are some important points to keep in mind when using this method:

    
    original_dict = {'a': 1, 'b': 2, 'c': 3}
    new_dict = {**original_dict}
    
    print("Original dict: ", original_dict)
    print("New dict: ", new_dict)
    

    <a id="h-6-summary-and-conclusion"></a>

    6. Summary and Conclusion

    In this article, we have learned how to do a deep copy of a python dictionary and edit them without affecting the original dict. We have learned about shallow copy and deep copy. You have learned different methods and the advantages of using them. I hope this article was helpful. Leave your questions in the comment section.

    Happy Coding!

    <a id="h-related-articles"></a>

    Related Articles