How can I write two dictionaries to be equal but not identical? [duplicate]

Solution 1:

The dictionaries store a reference to the list for each key here (because lists are mutable). If you copy the lists, the problem goes away

a={'a':[1,2],'b':[3,4]}
b={key:a[key].copy() for key in a}
b['b'][0]=5

Solution 2:

In b, when you say a[key], the value of that key is pointing to the same list which the value of relevant key in dictionary a points to. Instead you can do a deep copy. It takes care of any level of nesting for containers.

from copy import deepcopy

a = {'a': [1, 2], 'b': [3, 4]}
b = deepcopy(a)

b['b'][0] = 5
print(a)

output:

{'a': [1, 2], 'b': [3, 4]}