0

I want two dictionaries to be equal but not identical, so that I can modify one without changing the other. Here's an example on Python:

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

b={key:a[key] for key in a}

b['b'][0]=5

Everytime I do that I'm changing both b and a! How can I not do that?

2 Answers2

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]}
S.B
  • 13,077
  • 10
  • 22
  • 49
2

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
Kraigolas
  • 5,121
  • 3
  • 12
  • 37