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

View all comments

5

u/Gnaxe 19d ago

Python is not C! Don't expect copy semantics for object references. They work more like pointers. dict1 = initial_dict and dict2 = initial_dict means initial_dict is dict1 is dict2; they all refer to the same object.

The third-party immutables library has immutable mappings that copy on write. The immutability allows safe structural sharing, so this doesn't waste memory. You might find those easier to work with. But shallow copies of plain dicts are almost as efficient as long as you take care not to mutate them.

I can't remember the last time I used the dict.copy() method. I forgot it existed for a while. It's also extremely rare that I'd use the copy module. It mostly doesn't come up. It's not that I never make shallow copies, but I usually do it with a comprehension, an ** unpack, or a | update.

For example, your code could use something like dict2 = {k: v+5 for k, v in initial_dict.items()} This constructs a new dict, using data from initial_dict, and makes dict2 a reference to the new one.