0

I am trying to replace the value of a dict object. The following script works:

> d = {'a': 1}
> def f(d):
>     return {'b': 2}
> d = f(d)
> print d
{'b': 2}

But this one not:

> d = {'a': 1}
> def replace(d):
>     d = {'b':2}
> replace(d)
> print d
{'a': 1}

Why exactly?
And is it thus necessary to do d.pop(k) for all keys then d.update(...) to be able to change the entirety of a dict?

2 Answers 2

4

Rebinding is not the same thing as clearing a mutable value. You will have to clear the dictionary and give it new keys and values:

def replace(d):
    d.clear()
    d.update({'b': 2})

Names (variables) are just references to objects, and assigning a new dictionary to the local name d rebinds the name to the new object; the previous object is always unaffected.

You could make d a global, so that you'd rebind the global name to a new dictionary, but any other, remaining references would still point to an unaltered original dictionary. Clearing the actual dictionary object would work regardless of the number of references pointing to it.

Sign up to request clarification or add additional context in comments.

1 Comment

If the OP groks the difference between d[:] = [1] and d = [1] - this is that... :)
1

The d inside replace is a local variable and assigning to it won't replace the global dictionary d.

This can be fixed by using the global keyword.

However it may indeed be better to clear the dictionary and repopulate it with new values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.