Amit
Amit

Reputation: 33

Python: unusual behaviour dictionary update method

I am writing a script which builds a dictionary, and I observe a strange behaviour.

I will describe it below with a small example.

def test_f(parameter):
    parameter.update({'watermelon':'22'})
    return parameter

fruits = {'apple':20, 'orange': 35, 'guava': 12}
new_fruits = test_f(fruits)

In short, I have a dictionary which I pass to a function, test_f. The function appends a new dictionary to the input and returns it. I capture the output of the function in a variable called new_fruits. This however changes the original variable fruits too.

Why does the original variable fruits changes? Am I using the update method in an incorrect way?

Upvotes: 0

Views: 246

Answers (1)

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

No, you are using it right.

But lists, dictionaries etc are mutable types. And they will get updated even if you change them in a local scope. That because, python actually pass parameters by names, rather by values.

Read more from here.

Solution:

I will suggest you to make a new copy of dictionary and pass it as a parameter of your function. Use copy.deepcopy to copy the dictionary.

Change your function call like below:

import copy 

fruits = {'apple':20, 'orange': 35, 'guava': 12}
new_fruits = test_f(copy.deepcopy(fruits))

Upvotes: 5

Related Questions