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! :)

有帮助吗?

解决方案

def func(dct):
   dct.clear()
   dct.update({'a': 5})

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top