-2

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.

comhendrik
  • 239
  • 2
  • 11
  • `dict_to_return = dictionary` - this line makes both dicts point to the SAME dict. This is why you get 2 dicts changes. See https://docs.python.org/3/library/copy.html about creating a copy. – balderman Sep 08 '21 at 10:58
  • `dict_to_return = dictionary` creates another name for one dictionary. It doesn't make a copy. Try `dict_to_return = dictionary.copy()` – John Coleman Sep 08 '21 at 10:58
  • 3
    don't use `dict` as name – buran Sep 08 '21 at 10:59
  • 1
    Does this answer your question? [How to copy a dictionary and only edit the copy](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – buran Sep 08 '21 at 11:02

2 Answers2

1

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()

gpopides
  • 718
  • 5
  • 13
0

The reason is when you do dict_to_return = dictionary, it points to same directory and does not make a copy of it. The below code will work for you as expected:

import copy
dict1 = {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(copy.copy(dict1))
print(f'dict_save: {dict_save}')
dict1[5] = 6
print(f'dict_save: {dict_save}')
print(f'dict1: {dict1}')

Output:

dict_save: {5: 3, 6: 0}
dict_save: {5: 3, 6: 0}
dict1: {5: 6, 6: 0}
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16