Dictionary as input argument is being modified within function

0

In the code below the dictionary used as input argument is also being modified by the function. Do I have to% always%?

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}
    
asked by anonymous 05.10.2017 / 02:46

1 answer

1

If you do not want to modify the original dictionary you will need to copy the same one, 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
    
06.11.2017 / 16:38