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

2
  • stackoverflow.com/questions/2465921/… Commented Dec 4, 2016 at 8: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? Commented Dec 4, 2016 at 8:15

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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']}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.