Skip to content Skip to sidebar Skip to footer

Value In Python Dictionary Changes Unintentionally Even When Dictionary Was Not Referenced

I am trying to get a value from dictionary A, but somehow, through the 4th line(with the arrow), that changes the value of dictionary B. (dictA value is a dictionary of dictionary,

Solution 1:

If I understand your question correctly, the problem lies in your expectation of how Python objects behave. Python objects are accessed by reference, so if your object is shared in different data structures, modifying it will affect all these structures regardless whether you explicitly reference the object by its name, or otherwise.

Consider the following example:

import copy

list1 = [1, 2, 3]

# Both dict1 and dict2 share the same list1 object:
dict1 = {1: list1}
dict2 = {1: [], 2: list1}

# Modifying list1 affects all objects sharing it by reference:
dict1[1].append(4)
print(dict2)
# Prints# {1: [], 2: [1, 2, 3, 4]}# Alternatively, we can copy just the data by using copy.deepcopy, serializing and then# deserializing, etc. Cf:
list1 = [1, 2, 3]
dict1 = copy.deepcopy({1: list1})
dict2 = copy.deepcopy({1: [], 2: list1})

dict1[1].append(4)
print(dict2)
# Now prints# {1: [], 2: [1, 2, 3]}

In the first approach, dict1[1] points to list1, so modifying it essentially modifies list1, effectively changing dict2[2] (since it is a yet another reference to list1).

In the second part of the example, we explicitly perform a "deep" copy of the data to new objects, so they are not shared between the two dicts.

Post a Comment for "Value In Python Dictionary Changes Unintentionally Even When Dictionary Was Not Referenced"