0

I am new to programming so hopefully the answer will be easy. I was trying to set a dictionary equal to another dictionary, but whenever the second dictionary changed values, so did the first one. (without me telling it to.) For example

dictA = {'a':1}
dictB = {}
for x in range (1,5):
    dictB = dictA
    print "dictB is ",
    print dictB
    dictA['a'] += 1
    print "dictA is ",
    print dictA
    print "and dictB is ",
    print dictB

Returns:

dictB is  {'a': 1}
dictA is  {'a': 2}
and dictB is  {'a': 2}
dictB is  {'a': 2}
dictA is  {'a': 3}
and dictB is  {'a': 3}
dictB is  {'a': 3}
dictA is  {'a': 4}
and dictB is  {'a': 4}
dictB is  {'a': 4}
dictA is  {'a': 5}
and dictB is  {'a': 5}

Is there a way to maintain the value of dictB until the end of the loop? Thanks

Acoop
  • 2,586
  • 2
  • 23
  • 39
  • I do not agree with closing of this question based on this http://meta.stackoverflow.com/questions/251938/should-i-flag-a-question-as-duplicate-if-it-has-received-better-answers, I think the question and the answer are better presented here than in the original question. – Akavall May 23 '14 at 03:39

1 Answers1

3

That is because you are simply creating a reference to the same object. Try using copy.deepcopy or dict.copy() instead:

from copy import deepcopy

dictB = deepcopy(dictA)

Or:

dictB = dictA.copy()

Demo

a = {'a': 1, 'b': 2}

b = a

>>> print id(a)
2118820
>>> print id(b)     #same id
2118820

from copy import deepcopy

b = deepcopy(a)

print id(a)
2118820
print id(b)
1787364     #different id

Demo 2

a = {'a': 1, 'b': 2}

print id(a)

b = a.copy()

print id(b)

a['a'] = 5

print a,b

One thing to keep in mind about copy() is that:

dict.copy() creates a new dict with a different id, but just uses the same keys and values whereas deepcopy also copies the values. -@tdelaney

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • 1
    could you add some comments on why `dictB = dictA.copy()` does not work? – mitnk May 23 '14 at 03:16
  • `dict.copy()` will make a copy, and not "will give you a pointer to the same object" as you said. `.copy()` works for simple dicts without references in it. – mitnk May 23 '14 at 03:24
  • 2
    dict.copy creates a new dict with a different id, but just uses the same keys and values. deepcopy also copies the values. Deepcopy is useful when you have mutable types like lists and other dicts. In the example, a simple copy is all you need. – tdelaney May 23 '14 at 03:25
  • As it stands the answer is misleading; I would be happy to undo my -1 once the copy issue is explained. – Akavall May 23 '14 at 03:28
  • @Akavall, I hope my edit is sufficient enough – sshashank124 May 23 '14 at 03:34
  • @sshashank124, looks good to me. – Akavall May 23 '14 at 03:35