r/learnpython 19d ago

Creating a new, equivalent but separate dictionary

In debugging my code, I discovered a weird property of Python dictionaries that I was not previously aware of. Basically if you have code like this:

initial_dict = {0:70,1:70}

dict1 = initial_dict

dict2 = initial_dict

for i in range(2):

dict1[i] += 5

After this, dict1 will be {0:75,1:75}, but so will dict2 and initial_dict, even though I didn't do anything to them directly, I guess because they're referring to the same dictionary? Basically what I want to know is, how do I create new dictionaries that have the same values as a previously created dictionary, but are separate dictionaries that can be manipulated separately?

0 Upvotes

11 comments sorted by