0

I have a list of dictionaries as follows:

a = [{'a':1, 'b':2, 'c':3}, {'d':4, 'e':5, 'f':6}]

Now I want another list b to have same contents as a but with one (key,value) pair extra. So I do it as:

b = a.copy()
for item in b:
  item['x'] = 6

But now both the lists a and b have 'x': 6 sitting in them.

>>> b
[{'a': 1, 'b': 2, 'c': 3, 'x': 6}, {'d': 4, 'e': 5, 'f': 6, 'x': 6}]
>>> a
[{'a': 1, 'b': 2, 'c': 3, 'x': 6}, {'d': 4, 'e': 5, 'f': 6, 'x': 6}]

I also tried this:

c = a[:]
for item in c:
  item['q'] = 12

And now all the three lists have 'q': 12.

>>> c
[{'a': 1, 'b': 2, 'c': 3, 'x': 6, 'q': 12}, {'d': 4, 'e': 5, 'f': 6, 'x': 6, 'q': 12}]
>>> b
[{'a': 1, 'b': 2, 'c': 3, 'x': 6, 'q': 12}, {'d': 4, 'e': 5, 'f': 6, 'x': 6, 'q': 12}]
>>> a
[{'a': 1, 'b': 2, 'c': 3, 'x': 6, 'q': 12}, {'d': 4, 'e': 5, 'f': 6, 'x': 6, 'q': 12}]

I can't understand how is this working. This would have been acceptable if I had done b = a. But why for b = a.copy() and c = a[:].

Thanks in advance:)

  • - A shallow copy constructs a new compound object and then (to the extent possible) inserts *the same objects* into it that the original contains. – anon01 Feb 27 '21 at 06:51
  • - A deep copy constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original. – anon01 Feb 27 '21 at 06:51
  • ^^ from the documentation. You can access this quickly via `help(copy)` in a python shell – anon01 Feb 27 '21 at 06:52

2 Answers2

2

To copy a dictionary and copy all referenced objects use the deepcopy() function from the copy module instead of dict's method copy().

import copy
a = [{'a':1, 'b':2, 'c':3}, {'d':4, 'e':5, 'f':6}]
b = copy.deepcopy(d)
Ryan Laursen
  • 617
  • 4
  • 18
maziyank
  • 581
  • 2
  • 10
  • Thanks. This surely works but I want to know why the method I'm doing is not working:) – theProcrastinator Feb 27 '21 at 06:50
  • I edited it, but since it's not approved yet, copying a dictionary copies the dictionary's references. The objects it's referencing are the same objects, you need to do a deepcopy to copy the referenced objects as well. – Ryan Laursen Feb 27 '21 at 06:52
0

You can use @maziyank's solution. The explanation is that except copy.deepcopy() all the methods are just pointing one variable to the previous variable. Thus any change to any of them will transcend to all the variables that point to the same variable.

snowmanstark
  • 181
  • 7