How to copy a dictionary and only edit the copy

前端 未结 20 1981
说谎
说谎 2020-11-21 06:59

Can someone please explain this to me? This doesn\'t make any sense to me.

I copy a dictionary into another and edit the second and both are changed. Why is this hap

20条回答
  •  余生分开走
    2020-11-21 07:45

    The best and the easiest ways to create a copy of a dict in both Python 2.7 and 3 are...

    To create a copy of simple(single-level) dictionary:

    1. Using dict() method, instead of generating a reference that points to the existing dict.

    my_dict1 = dict()
    my_dict1["message"] = "Hello Python"
    print(my_dict1)  # {'message':'Hello Python'}
    
    my_dict2 = dict(my_dict1)
    print(my_dict2)  # {'message':'Hello Python'}
    
    # Made changes in my_dict1 
    my_dict1["name"] = "Emrit"
    print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
    print(my_dict2)  # {'message':'Hello Python'}
    

    2. Using the built-in update() method of python dictionary.

    my_dict2 = dict()
    my_dict2.update(my_dict1)
    print(my_dict2)  # {'message':'Hello Python'}
    
    # Made changes in my_dict1 
    my_dict1["name"] = "Emrit"
    print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
    print(my_dict2)  # {'message':'Hello Python'}
    

    To create a copy of nested or complex dictionary:

    Use the built-in copy module, which provides a generic shallow and deep copy operations. This module is present in both Python 2.7 and 3.*

    import copy
    
    my_dict2 = copy.deepcopy(my_dict1)
    

提交回复
热议问题