Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the content of dictionary with another dictionary in a function - Python

I have a dictionary, and I want to pass it as argument to a function. After executing this function, I want the dictionary changed.

Here is my try:

def func(dict):
    dict = {'a': 5}

So what I want to happen:

dict = {'b': 3}
func(dict)
print(dict) # to be {'a': 5}, not {'b': 3}

Is there a way to achieve this? Thank you very much in advance! :)

like image 326
Faery Avatar asked Apr 18 '14 17:04

Faery


2 Answers

def func(dct):
   dct.clear()
   dct.update({'a': 5})
like image 81
mgilson Avatar answered Nov 04 '22 13:11

mgilson


You can mutate a dictionary within a method, because it is passed by reference, but in your case you're simply creating a new dictionary altogether. Since your variable dict is within a method, it doesn't share the same scope as the outer contents, and so refers to a new variable. If you want to overwrite it altogether, consider:

def func(dct):
    return {'a': 5}

dct = func(dct)

The only benefit that I can see from completely wiping an existing dictionary and updating it with new content is if it had multiple other references which you also wished to update. If this isn't the case I'd suggest you just create a new dictionary. If the old dictionaries ref count drops to zero then it'll be garbage collected, so I don't see any great memory benefits.

like image 6
Ian Clark Avatar answered Nov 04 '22 13:11

Ian Clark