Dictionary as input argument is being modified within the function

Asked

Viewed 304 times

1

In the code below the dictionary used as input argument is also being modified by the function. I need to perform a deepcopy() at all times?

def muda(a):
    a['valor'] = 50
    return a

dic1 = {'valor': 12}
dic2 = muda(dic1)
print(dic1)
{'valor': 50}
print(dic2)
{'valor': 50}

from copy import deepcopy
dic1 = {'valor': 12}
dic2 = muda(deepcopy(dic1))
print(dic1)
{'valor': 12}
print(dic2)
{'valor': 50}
  • Dictionary is a changeable type, so its passage through the parameter is by reference. If it makes sense to change the value within the function, but you don’t want this change to be reflected out of the function, you actually have to copy the object.

1 answer

1

If you do not want to modify the original dictionary it will be necessary to copy it, because the dictionary is passed by reference and not by copy. You can also use Dict:

def muda(a):
    a = dict(a)
    a['valor'] = 50
    return a

Browser other questions tagged

You are not signed in. Login or sign up in order to post.