0

I have a problem with dictionary. See samples.

dict1 = {"key1" : "value1","key2" : "value2"}
tempdict1 = dict1
dict1.pop("key1")
print(dict1) #returns {"key2":"value2"}
print(tempdict1) #returns {"key2":"value2"} also.

The dict1 works as expected but the tempdict1 also have the same value as dict1.

I am using Python 2.7.

Thanks!

aldesabido
  • 1,268
  • 2
  • 17
  • 38

1 Answers1

1

That's because you copy the reference th the dictionary, not the dictionary itself. Instead of:

tempdict1 = dict1

you should write

tempdict1 = dict(dict1)

to create a copy that you can alter independently.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    prefer use [`deepcopy`](https://docs.python.org/2/library/copy.html#copy.deepcopy) this will help only on one level of dictionary. `d1 = {'a': {'b':3}, 'c': 4};d2['a'].pop('b')` will change also the `d1` object – ShmulikA Jan 24 '17 at 11:27
  • Yeah of course bit since the example shows strings and strings are immutable, there is "second level" so to speak. – Willem Van Onsem Jan 24 '17 at 11:28