0

I have this dictionary,

dict = {'A':np.random.rand(2,2), 'B':np.random.rand(2,2)}

For some reasons, I need to to get a copy of items inside this dictionary and manipulate them as follows,

for key, value in dict.items():
    tmp = value
    tmp[1, 1] = 0

This actually changes the original values inside the dict! If I get a print, for example of the first entry, I will see:

Initial value
[[0.46905019 0.5143053 ]
[0.9083885  0.62560836]]
Final Value
[[0.46905019 0.5143053 ]
[0.9083885  0.        ]]

So, how I can have a copy of dictionary items and manipulate them without changing the original values? Of course, one trivial solution is to make a copy of dictionary and work with the copy, but is there any other solution? And more importantly, is this behavior intentional or it is kind of unwanted?

Esi
  • 33
  • 4
  • You never call anything to make a copy of `value`. Probably look into `numpy.copy` – h4z3 Jul 10 '19 at 14:03
  • Making a shallow copy of the whole dictionary is not enough. You would need [`deepcopy`](https://docs.python.org/3/library/copy.html#copy.deepcopy). – Matthias Jul 10 '19 at 14:03
  • `tmp` and `value` are refering to the same objects, as you can check by comparing `id(tmp)` and `id(value]` (python 3). For CPython the id is the address of the object in memory. – Stef Jul 10 '19 at 14:11

1 Answers1

0

you can use .copy() like this:

for key, value in dict.items():
    tmp = value.copy()
    tmp[1, 1] = 0
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38