Home > Blockchain >  Two dictionary variables point to the same object however they affect eachother
Two dictionary variables point to the same object however they affect eachother

Time:04-05

I noticed a weird behaviour in Python, where two dictionaries are affecting each-other, even though they are separate variables (and pointing to different memory location I guess). Below is a simple python3 script for PoC:

first_dict = {'hello' : '1', 'oops': '2'}
second_dict = first_dict

#let's delete a value from first_dict
del first_dict['hello']

#output of the second dictionary which is supposed to be unchanged
print(second_dict)

Output is:

{'oops': '2'}

What can I do so the second array doesn't get affected by the first array?

CodePudding user response:

It's not strange behavior. You're simply assigning a new variable to the same object. This is the case for lists and I'm sure other iterable objects in Python. But Here's the way around it. Using deepcopy() ensures that any nested data also gets copied and thus an entirely new object in memory is created.

import copy

first_dict = {'hello' : '1', 'oops': '2'}
second_dict = copy.deepcopy(first_dict)


del first_dict['hello']


print(second_dict)

If I were to use copy.copy(), nested values would not be copied. For example, try this out to see how it behaves:

import copy

first_dict = {
    'hello' : '1', 
    'oops': {
        'nested value': 'eh oh',
    },
}
second_dict = copy.copy(first_dict)

del first_dict['hello']
del first_dict['oops']['nested value']

print(second_dict)
  • Related