Search code examples
pythondictionaryreturn-value

Save dictionary in a variable python


I have a dictionary and I want to work with it and make some changes to it with my function. After the changes I want to save the dictionary in a variable to compare it after I did some other changes but when I print after the second change, the value isn't the same. My Example:

dict = {5:0,6:0}

def increase_values(dictionary):
    dict_to_return = dictionary
    dict_to_return[5] = 3
    return dict_to_return

dict_save = increase_values(dict)

print(dict_save)

dict[5] = 6

print(dict_save)

print(dict)

The first time I print dict_save the ouput will be {5: 3, 6: 0} The second time I print dict save the Output will be {5: 6, 6: 0} When I print dict the Output will be {5: 6, 6: 0} and this is clear for me why but I don't know why the value of dict_save changed too. I need the same value of dict_save after changing dict a second time.


Solution

  • First, don't use dict as a variable name because it is a keyword in python.

    Second, when you do dict_to_return = dictionary, you are essentially having the same reference to the object, so when you modify 1, the other one gets modified also.

    What you can do is, dict_to_return = dictionary.copy(), which will create a new dict.

    Keep in mind that if your dict is big, that can get slow.

    Have a look at dict.copy()