2

I am using dictionary as argument to the function.

When i Change the values of the argument passed, it getting changed parent dictionary.i have used dict.copy() but still not effective.

How to avoid mutable in dictionary values. Need your inputs

>>> myDict = {'one': ['1', '2', '3']}
>>> def dictionary(dict1):
    dict2 = dict1.copy()
    dict2['one'][0] = 'one'
    print dict2


>>> dictionary(myDict)
{'one': ['one', '2', '3']}
>>> myDict
{'one': ['one', '2', '3']}

My intention was my parent dictionary should be changed. Thanks, Vignesh

Vignesh
  • 41
  • 1
  • 4
  • http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy – jkr Dec 04 '16 at 08:13
  • 1
    "My intention was my parent dictionary should be changed." That is what is happening. Did you mean to say your intention is that it should *not* be changed? – BrenBarn Dec 04 '16 at 08:15

2 Answers2

4

Use deepcopy() from the copy module.

from copy import deepcopy
myDict = {'one': ['1', '2', '3']}
def dictionary(dict1):
    dict2 = deepcopy(dict1)
    dict2['one'][0] = 'one'
    print dict2

See the docs:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
SheepPerplexed
  • 1,132
  • 8
  • 20
jkr
  • 17,119
  • 2
  • 42
  • 68
1

You can use deepcopy from copy module like this example:

from copy import deepcopy

myDict = {'one': ['1', '2', '3']}

def dictionary(dict1):
    dict2 = deepcopy(dict1)
    dict2['one'][0] = 'one'
    print  dict2

dictionary(myDict)
print(myDict)

Output:

dict2 {'one': ['one', '2', '3']}
myDict {'one': ['1', '2', '3']}
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43