Bogdan Osyka
Bogdan Osyka

Reputation: 1983

Passing dictionary as an input parameter to a function global/local variable issue

Hi can anyone clarify this issue for me. Here is a sample of the code:


def test1(d1):
    d1_adj = d1.copy()
    d1_adj.get(0)[0] *= 10
    return d1_adj

d1 = {0: [10, 10]}
d1_adj = test1(d1)
print d1
{0: [100, 10]}

Why does d1 dictionary get updated and how can I come across this issue if I want to preserve that values of the original input dictionary and only update the values of the one that has been copied

Thanx

Upvotes: 2

Views: 151

Answers (2)

ilim
ilim

Reputation: 4547

copy does a shallow copy, and not a deep copy, as you intended to do. Consequently, it does not create a copy of the entire list at key 0, and modifies the original list.

You may perform a manual deep copy of the values within the dictionary by traversing it once. Or better still, unless there are any requirements against using it, you may utilize copy module to perform deep copy(i.e. copy.deepcopy) operation. All you need to do is to update your test1 function as follows.

from copy import deepcopy

def test1(d1):
    d1_adj = deepcopy(d1)
    d1_adj.get(0)[0] *= 10
    return d1_adj

Upvotes: 3

Abhijith Asokan
Abhijith Asokan

Reputation: 1875

It is because d.copy() is shallow copy. You need deep copy to accomplish this.

from copy import deepcopy

Then

d1_adj = deepcopy(d1)

Upvotes: 5

Related Questions